Friday 26 August 2016

javascript - How does the following piece of expression evaluates to "10"





I have recently seen an expression from a source, which looks something like below -



++[[]][+[]]+[+[]]


Entering this into the Chrome (Windows 7, Version 27.0.1453.94 m) console shows a result of "10".



Can someone explain what's happening here?



JSFiddle.



Answer



JavaScript is fairly flexible about converting between data types. The first thing to notice is that +[] evaluates to 0.* That lets us rewrite the expression as:



++[[]][0] + [0]


The next thing to notice is that ++[[]][0] is the preincrement operator applied to the first element of [[]]. Normally you can't apply ++ to an array, but JavaScript kindly converts the first element to 0, so the result is that ++[[]][0] evaluates to 1 (the first element of [[]] having now been incremented). It is kind of like this:



var a = [[]];
var b = ++a[0];

// now a will be [1] and b will be 1


That leaves us with:



1 + [0]


JavaScript now converts the int and the array to strings (since [0] is not a numeric value) and concatenates them together. Done!




* My understanding of how +[] becomes 0 is that it is a two-step process: first, [] is converted to a string primitive, which is the empty string. The empty string then converts to a number, which is zero. Via the same route, [1] evaluates to '1' and then to 1, [2] evaluates to 2, etc. However, [1, 2] evaluates to '1,2' which evaluates to NaN. (The last because the decimal point separator is ., not ,. I don't know what would happen if my locale were different.)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...