0

Now I meet one strange JavaScript expression console.log(({}+[])[+[]]), and I try to understand it with following test.

  1. console.log([]) output []

  2. console.log(+[]) output 0

So [+[]] equals to [0], I guess it seems like an array. However, I can NOT figure out the whole expression ({}+[])[+[]] means?

Based on the second expression, I think we can get 1. and I make it through console.log(+!![]), but when I try to make 2 by console.log(+!![]++!![]), it failed.

Here is my idea 2 = 1 + 1, so +!![]++!![] means (+!![]) + (+!![]). Can anyone help me figure out why it failed?

zangw
  • 43,869
  • 19
  • 177
  • 214
  • 1
    similar http://stackoverflow.com/questions/9032856/what-is-the-explanation-for-these-bizarre-javascript-behaviours-mentioned-in-the, http://stackoverflow.com/questions/17014770/why-and-how-does-evaluate-to-the-letter-i – Musa Dec 28 '14 at 01:10

1 Answers1

2

This does nothing useful. Like you said, it gets [0] from the result of ({}+[]), which is [:

  1. ({}+[]) == '[object Object]' because you're concatenating two objects that don't have a regular way of adding together, so this just returns that the thing between the brackets is an object,
  2. '[object Object]'[0] == '[' because [0] always gets the first character of a string (strings are treated as arrays containing single letters).

Considering your second part of the question, it doesn't work because there are two plus signs next to each other, so it assumes you're using postfix incrementation (like i++ in loops). Simply adding a space between the spaces will fix this:

console.log(+!![]+ +!![])
> 2

but, since you're adding the boolean value of the array anyway, which is 1 here, you could also leave the prefix + out, since the expression already converts this boolean value to a number:

console.log(!![] + !![])
> 2

The !! part simply converts the thing coming after it to a boolean. Since !myVar returns a boolean opposite to the boolean value of myVar, !(!myVar), which is the same as !!myVar would return a boolean opposite of that. In this case, myVar would be your empty array [].

Joeytje50
  • 18,636
  • 15
  • 63
  • 95