Skip to content

Instantly share code, notes, and snippets.

@therajumandapati
Created June 10, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therajumandapati/5b5e680cc0b5dd275a3b to your computer and use it in GitHub Desktop.
Save therajumandapati/5b5e680cc0b5dd275a3b to your computer and use it in GitHub Desktop.
JavaScript for Amateurs
+[] 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”
@butchpeters
Copy link

For context, this was in reply to:

"Can someone explain why ++[[]][+[]]+[+[]] executes to "10" in JavaScript ?"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment