Easily assign default values while destructuring objects.
Consider below code-
|
|
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 -
|
|
What’s happening here -
- Javascript tries to assign
x
,y
,z
variables to props in object. - Only
x
is found in object and the value is promptly updated to variablex
z
is not defined and is assigned the default value1
y
staysundefined
since there is no value present in the object and no default value is specified