Posts tagged "es6"

Destructuring assignment features in es6

Today I learned about the helpful ES6 "destructuring" feature to unpack arrays and objects.
It is a convenient way to extract values into distinct variables.

It is possible to object-destructure arrays:

const { 0: x, 2: y, 3: z } = ['a', 'b', 'c', 'd'];
console.log(x) // 'a'
console.log(z) // 'd'

This works because array indices are properties as well!

Alternatively, array-destructuring can be applied to any value that is iterable, not just to arrays:

// Sets are iterable
const mySet = new Set().add('a').add('b').add('c');
const [first, second] = mySet;
console.log(first) // 'a'
console.log(second) // 'b'

// Strings are iterable
const [a, b] = 'xyz';
console.log(a) // 'x'
console.log(b) // 'y'