Created
June 10, 2015 13:58
-
-
Save therajumandapati/5b5e680cc0b5dd275a3b to your computer and use it in GitHub Desktop.
JavaScript for Amateurs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+[] evaluates to the number zero, because unary-plus tries to convert any value to a number, so that leaves | |
++[[]][0]+[0] | |
[[]][0] is an expression accessing the first element in the array, which is a reference to the inner array. This is shorthand for x = [[]]; x[0];, if it helps you see it better. | |
++[[]][0] then evaluates to a pre-increment of the first element in the array, which returns the value after the element is incremented. Because an array is not numeric, it first needs to coerce it to a number. We saw before that an empty array coerces to 0, so incrementing 0 is 1. If we had a reference to [[]], we’d see that it becomes [1] after the increment operation. (i.e. x = [[]]; ++x[0] // returns 1, and x is now [1]) | |
So, this whole expression boils down to 1 + [0]. Since a number and an array can’t normally be added together, javascript converts both values to strings and concatenates them. | |
1.toString() + [0].toString() | |
“1” + “0” | |
“10” |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For context, this was in reply to:
"Can someone explain why ++[[]][+[]]+[+[]] executes to "10" in JavaScript ?"