Ervin Szilagyi
Ervin Szilagyi

Reputation: 16795

Why does [[]][0]++ work but []++ throws run-time exception?

Why does the first line work while the second line throws run-time exception?

The first line:

[[]][0]++; //this line works fine

The second line:

[]++; //this lines throws exception

Upvotes: 24

Views: 1028

Answers (3)

6502
6502

Reputation: 114569

This is a rare case in which Javascript does something that actually makes sense. Consider

x[3]++; // Valid
3++;    // Not valid

If this make sense for you, then what is surprising about

[[]][0]++; // valid
[]++;      // not valid

<array>[index] is "a place" that you can assign or increment. That's all. The fact that you can increment a[<expr>] doesn't imply that you can increment <expr>.

The absurd part is that you can use [] as an index, that has the meaning of converting the array to an empty string "" and then to the number 0, but this is the well known problem of absurd implicit conversions of Javascript. Those implicit conversion rules are a big wart of Javascript and for example imply that 1 == [1] or that both []==false and (![])==false.

Javascript is pure nonsense in a lot of places... but not really here.

Upvotes: 5

Nikolai
Nikolai

Reputation: 3134

The ++ operator (or indeed any postfix operator) requires the operand to be a "reference" - that is, a value that can be assigned to. [] is a literal, so you can't assign to it. [[]][0] is a valid reference to an element of a temporary array.

0++; // not valid, `0` is a literal.
var a = [];
a++; // ok, `a` is assignable

Upvotes: 11

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

[[]][0]++

is equivalent to

var tmp = [[]];
tmp[0] = tmp[0]+1;

tmp[0] is an empty array, which is cast to the number 0, which increments to 1.

This only works because <array>[<index>]++ looks valid. It takes some type juggling, but it gets there.

But []++ is outright invalid. There's no way to make it make sense.

[] = []+1;

The left-hand side here is indeed invalid. You can't assign to an empty array.

Upvotes: 18

Related Questions