Operator
Equivalent
x &= y
x = x & y
x |= y
x = x | y
x ^= y
x = x ^ y
Destructuring Assignment
New in ES6 is a welcome feature called destructuring assignment that allows you to
take an object or an array, and “destructure” it into individual variables. We’ll start
with object destructuring:
// a normal object
const
obj
=
{
b
:
2
,
c
:
3
,
d
:
4
};
// object destructuring assignment
const
{
a
,
b
,
c
}
=
obj
;
a
;
// undefined: there was no property "a" in obj
b
;
// 2
c
;
// 3
d
;
// reference error: "d" is not defined
When you destructure an object, the variable names must match property names in
the object (array destructuring can only assign property names that are identifiers).
In this example,
a
didn’t match any property in the object, so it received the value
undefined
. Also, because we didn’t specify
d
in the declaration, it was not assigned to
anything.
In this example, we’re doing declaration and assignment in the same statement.
Object destructuring can be done on assignment alone, but it must be surrounded by
parentheses; otherwise, JavaScript interprets the lefthand side as a block:
const
obj
=
{
b
:
2
,
c
:
3
,
d
:
4
};
let
a
,
b
,
c
;
// this produces an error:
{
a
,
b
,
c
}
=
obj
;
// this works:
({
a
,
b
,
c
}
=
obj
);
With array destructuring, you can assign any names you want (in order) to the ele‐
ments of the array:
// a normal array
const
arr
=
[
1
,
2
,
3
];
// array destructuring assignment
98 | Chapter 5: Expressions and Operators