Why JavaScript “++[[]][+[]]+[+[]]” expression returns string “10”

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:

  1. 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:
    ++[[]][0]+[0]
    

  2. Now we can split it to two three separate expressions:

    ++ // Increment operator
    [[]][0] // Which returns [], that casts to 0 and then incremented to 1 (++ always returns a number)
    +[0] // Which returns 0
    

  3. [[]][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:

    [[]][0] // [], or
    [[]].pop() // []
    

  4. 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:

    ++[[]][0] // 1
    ++[[]][0] === +([] + 1) // true
    +([] + 1) === 1 // true
    

  5. And the last part + [0], when we add array to anything in JavaScript, it will concatenate it to string of values with commas:

    0 + [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:

++ // 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
]