let
[
x
,
y
]
=
arr
;
x
;
// 1
y
;
// 2
z
;
// error: z hasn't been defined
In this example,
x
is assigned the value of the first element in the array, and
y
is
assigned the value of the second element; all elements past that are discarded. It’s pos‐
sible to take all the remaining elements and put those in a new array with the spread
operator (
...
), which we’ll cover in
const
arr
=
[
1
,
2
,
3
,
4
,
5
];
let
[
x
,
y
,
...
rest
]
=
arr
;
x
;
// 1
y
;
// 2
rest
;
// [3, 4, 5]
In this example,
x
and
y
receive the first two elements, and the variable
rest
receives
the rest (you don’t have to name the variable
rest
; you can use whatever name you
want). Array destructuring makes it easy to swap the values of variables (something
that previously required a temporary variable):
let
a
=
5
,
b
=
10
;
[
a
,
b
]
=
[
b
,
a
];
a
;
// 10
b
;
// 5
Array destructuring doesn’t only work on arrays; it works on any
iterable object (which we’ll cover in
In these simple examples, it would have been easier to simply assign the variables
directly instead of using destructuring. Where destructuring comes in handy is when
you get an object or array from elsewhere, and can easily pick out certain elements.
We’ll see this used to great effect in
Object and Array Operators
Objects, arrays, and functions have a collection of special operators. Some we have
already seen (such as the member access and computed member access operator),
and the rest will be covered in Chapters
,
. For completeness, they are sum‐
marized in
.
Object and Array Operators | 99