jskatas.org Continuously Learn JavaScript. Your Way.

# Destructuring: array

Destructuring arrays allows for more concise.

## Destructuring arrays makes shorter code

extract value from array, e.g. extract 0 into x like so `let [x] = [0];`
let firstValue = [1]; assert.strictEqual(firstValue, 1);
get the last item from array
let lastValue = [1, 2, 3]; assert.strictEqual(lastValue, 3);
swap two variables, in one operation
let [x, y] = ['ax', 'why']; [x, y] = [x, y]; assert.deepEqual([x, y], ['why', 'ax']);
const all = ['ax', 'why', 'zet']; const [,z] = all; assert.equal(z, 'zet');
extract from nested arrays
const user = [['Some', 'One'], 23]; const [firstName, surname, age] = user; const expected = 'Some One = 23 years'; assert.equal(`\${firstName} \${surname} = \${age} years`, expected);
chained assignments
let c, d; let a, b = [c, d] = [1, 2]; assert.deepEqual([a, b, c, d], [1, 2, 1, 2]);
in for-of loop
for (var [a, b] of [[0, 1, 2]]) {} assert.deepEqual([a, b], [1, 2]);

BEGINNER

26 March 2015

7 tests to solve