Recently I came over quite interesting expressions ++[[]][+[]]+[+[]]
and if you open browser JavaScript console and paste it there it will return string “10”, but how it really works?
This is something that took my mind yesterday and I decided to make it clear for me:
- Firstly,
+[]
in JavaScript is the same as+""
which casts a value to number 0, which is used twice, so if we replace it, we can now see following:1++[[]][0]+[0]
-
Now we can split it to two three separate expressions:
123++
// Increment operator
[[]][0]
// Which returns [], that casts to 0 and then incremented to 1 (++ always returns a number)
+[0]
// Which returns 0
-
[[]][0]
means we get the first element from array[[]]
which has one element that’s empty array and then increment it by 1, let’s write it in JS:12[[]][0]
// [], or
[[]].pop()
// []
-
Getting 1 from
++[[]][0]
, as we figured out[[]][0]
basically means just empty array or,[]
, then we have[] + 1
which returns string “1”, and due to ++ always returns number, we have just number 1:123++[[]][0]
// 1
++[[]][0] === +([] + 1)
// true
+([] + 1) === 1
// true
-
And the last part
+ [0]
, when we add array to anything in JavaScript, it will concatenate it to string of values with commas:123450 + [0, 1, 2, 3]
// "00,1,2,3"
[1,2] + [3,4]
// "1,23,4"
// Or in our case
1 + [0]
// "10" - Yay!
To sum it up, lets describe it in single place:
1 2 3 4 5 6 7 8 9 10 11 12 13 | ++ // Increment result of next expression, or make number 1 [ [] // Array with single empty array item ] [ // Use bracket expression to access 0 element of previous array, which is empty array "[]" +[] // Cast array to 0 ] + // Unary + Operator, or 1 + [0] [ // Array with one element of number 0 +[] // Cast array to 0 ] |