2

I was reading through Kyle Simpson's book (You don't Know JS - ES6 and beyond) and he gives this example on reordering arrays:

 var a1 = [ 1, 2, 3 ],
    a2 = [];

[ a2[2], a2[0], a2[1] ] = a1;

console.log( a2 );                  // [2,3,1]

Can someone help me understand what's happening (I was expecting it to return [3, 1, 2]). If I input other elements, it gets more confusing:

[ a2[2], a2[0], a2[0] ] = a1; // [3, undefined, 1]
[ a2[1], a2[0], a2[0] ] = a1; // [3, 1]

4 Answers 4

3

You can use Babel's REPL to find out what the code compiles down to. (I've annotated the output with additional comments.)

var a1 = [1, 2, 3],
    a2 = [];

a2[2] = a1[0];  // a1[0] = 1
a2[0] = a1[1];  // a1[1] = 2
a2[1] = a1[2];  // a1[2] = 3
console.log(a2); // [2,3,1]
Sign up to request clarification or add additional context in comments.

Comments

1

The positions in the destructuring pattern map to the indexes in the source array. So it's equivalent to:

a2[2] = a1[0];
a2[0] = a1[1];
a2[1] = a1[2];

The result you were expecting would come from:

a2 = [ a1[2], a1[0], a1[1] ];

This is the opposite of destructuring.

This one:

[ a2[2], a2[0], a2[0] ] = a1;

never assigns to a2[1], so you get undefined for that element. You assign to a2[0] twice, first from 2 and then from 3, so the final value is 3.

Comments

1

It's actually quite simple.

Destructing an array in ES6 is basically like this:

If you have

var arr = [1, 2, 3, 4];

This means that when you write something like

[a, b, c, d] = arr;

You are actually saying this

a = arr[0];
b = arr[1];
c = arr[2];
d = arr[3];

Notice that the position of a, b, c or d corresponds to the index of the array arr, such that if you write

[a, c, b, d] = arr;

What you really mean is

a = arr[0];
c = arr[1];
b = arr[2];
d = arr[3];

Comments

0

It just combine two steps of destructuring and adding values to arr2 in one step. It is same as if you did this.

 var a1 = [1, 2, 3],
   a2 = [];

var [one, two, three] = a1;
a2[0] = two;
a2[1] = three;
a2[2] = one
console.log(a2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.