Easily assign default values while destructuring objects.
Consider below code-
const obj = { x: 9, y: 1 };
const { x, y } = obj;
console.log(x, y);
// 9 1
A typical destructuring of objects, this code assigns x and y variables to the x/y props of object obj.
This is a-ok, but what if you want to specify defaults in case any of the props are not present? Such defaults help avoid unexpected errors during further processing.
Consider below code -
const obj = { x: 9 };
const { x, y, z = 1 } = obj;
console.log(x, y, (z = 1));
// 9 undefined 1
What’s happening here -
- Javascript tries to assign
x,y,zvariables to props in object. - Only
xis found in object and the value is promptly updated to variablex zis not defined and is assigned the default value1ystaysundefinedsince there is no value present in the object and no default value is specified