2

After watching this question, I came to know

let a = [1, 2] [3, 4] = [5, 6];

console.log(a);

is valid JavaScript code but, I'm not able to understand, how it is working. Can anyone explain working flow of above code.

Rehan Haider
  • 893
  • 11
  • 26

1 Answers1

3

After executing a lot of variations of

let a = [1, 2] [3, 4] = [5, 6];

I came to know

[1, 2] [3, 4] is equivalent to [1, 2][4] where [1, 2] represents an array while [4] represents 5th index of [1, 2] array but could not find any official documentation.

Update I was wrong about documentation as mentioned in comments, [] in [3, 4] is Property accessor while 3, 4 are two different code statements separated by Comma operator. In comma operator, every statement separated by , is executed from left to right and result of last statement is returned.

Above code now simplifies to

let a = [1, 2][4] = [5, 6];

which is comparatively easy to understand. If we simplify it little bit more it becomes

let arr = [1, 2];
let a = arr[4] = [5, 6];

console.log(a);
console.log(arr);

Now it is very easy to explain it arr[4] = [5, 6] assigns [5, 6] to 5th index of arr and a = arr[4] assigns 5th index of arr to a which is now [5, 6] so [5, 6] is assigned to a.

Now current value of a is [5, 6] and current value of arr is [ 1, 2, undefined, undefined, [ 5, 6 ] ]

Lets rewrite above code again

let arr = [1, 2];
let a = arr[3, 4] = [5, 6];

console.log(a);
console.log(arr);
Rehan Haider
  • 893
  • 11
  • 26
  • 2
    `3, 4` is an expression that uses the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator). Both sub-expressions joined by a comma operator are evaluated and the value of the expression is the value of the last sub-expression. In this example, the value of expression `3, 4` is `4`. – axiac Mar 15 '18 at 07:49
  • 1
    _“could not find any official documentation”_ — how about [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) and [property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors)? – Sebastian Simon Mar 15 '18 at 07:49
  • Thanks @axiac and Xufox for pointing about comma operator, let me update my answer – Rehan Haider Mar 15 '18 at 07:51