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.
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.
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);