Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: [] = 5, No Syntax Error? Why?

Tags:

javascript

Yeah, it works in my firebug console. Why does something like this present no syntax error?

[] = 5; [] = doThis(); [] = (function() {})();

Just curious about why it's allowed.

like image 825
Iggyhopper Avatar asked Jul 07 '10 01:07

Iggyhopper


2 Answers

Looks like Javascript in FF allows assignment using matching so you can set multiple variables in one shot:

[x,y] = [5,6]; // sets x to 5 and y to 6

"Obviously", some JS implementations are very forgiving, and will silently ignore any extra values, so this does the same:

[x,y] = [5,6,7];

and this would just not assign anything:

[] = [5,6,7];

and on top of that, it looks like FF is even willing to go with a case that doesn't match an array at all:

[x] = 5; // makes x undefined

so if you use [] = whatever then "nothing gets assigned an undefined value", so it boils down to just evaluating the RHS.

(Disclaimer: this is all just guessing the meaning by running stuff in FF...)

like image 118
Eli Barzilay Avatar answered Sep 22 '22 22:09

Eli Barzilay


I get a "Uncaught ReferenceError: Invalid left-hand side in assignment" in Chrome. IE8 throws "Error: Cannot assign to '[object]'". FF does, indeed, not throw an error.

This is most likely just a failing of the Firefox JavaScript engine, and in any case, does not seem to affect the functionality of the array literal [].

like image 30
Ryan Kinal Avatar answered Sep 20 '22 22:09

Ryan Kinal