Ambiguous array assignments in JavaScript [duplicate]

163
March 15, 2018, at 5:34 PM

This question already has an answer here:

  • Why does [5,6,8,7][1,2] = 8 in JavaScript? 4 answers

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.

Answer 1

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

READ ALSO
JS load script dynamically in index html and block

JS load script dynamically in index html and block

I want to load a script that loads another script based on condition and this script is adding a variable to the global window

283
Clipper.js not working with set of coordinates

Clipper.js not working with set of coordinates

I am trying to adapt the 'simplify polygon' function from the the clipperjs library

166
Not able to access current location using simple HTML code

Not able to access current location using simple HTML code

I have written the following code to access my location, but this code is not showing my current location

175
can someone tell me the why we need decodeURIComponent

can someone tell me the why we need decodeURIComponent

I have this piece of code that I couldn't find any explanation forWhen I googled decodeURIComponent it said it is the reverse of encodeURIComponent, however, I can't find encodeURIComponent anywhere in my code

141