Member-only story
Best of Modern JavaScript — Destructuring and Defaults
Since 2015, JavaScript has improved immensely.
It’s much more pleasant to use it now than ever.
In this article, we’ll look at JavaScript destructuring.
Array Patterns Work with Iterable Object
We can use array patterns like the rest operator with iterable objects.
For example, we can write:
const [x, ...y] = 'foo';
The x
is 'f'
and y
is ['o', 'o']
.
Since strings are iterable, we can destructure them.
Destructuring also works with string code points.
For example, we can write:
const [x, y, z] = 'a\uD83D\uDCA9c';
The x
is 'a'
, b
is '\uD83D\uDCA9'
and z
is 'c'
.
Default Values
We can set default values when destructuring.
For example, we can write:
const [x = 13, y] = [];
Then x
is 13 and y
is undefined
since the array is empty.
Since 13 is the default value of x
, it’s assigned to it.