-1

This is valid and returns the number 1 in JavaScript:

++[[]][0]

Why doesn't it reporting an error like ++[]?

Isn't it the same as ++[]?

NOTE: This is a bit different than: Why does ++[[]][+[]]+[+[]] return the string “10”.

What I mean is that why doesn't ++[[]][0] report an error? Is [[]][0] a variable? If not, why doesn't it report the error like:

++[] // returns Invalid left-hand side expression in prefix operation.
Community
  • 1
  • 1
Marco
  • 131
  • 1
  • 7
  • 2
    http://stackoverflow.com/questions/7202157/why-does-return-the-string-10?rq=1. While not an *exact* duplicate, it's close enough and gives you the pieces to figure your question out. – j08691 Jun 15 '16 at 13:39
  • The real question is, why would you ever write this code in the first place? – Heretic Monkey Jun 15 '16 at 13:40

1 Answers1

3

The prefix increment operator (++) calls PutValue, and PutValue throws a ReferenceError when the argument is not a Reference.

So in the same way that

var a = [];
++a; // returns 1

is valid because a is a Reference to [], but ++[] is not valid because [] is an array literal, not a reference.

Similarly, [[]][0] is a Reference to [], so incrementing that Reference is again, valid.

This is also similar to

++1 // throws ReferenceError
var a = 1;
++a // returns 2
romellem
  • 5,792
  • 1
  • 32
  • 64