matvs
matvs

Reputation: 1873

Why ++[] throws an error but ++[[]][0] produces 1?

What is the difference between these two following expressions? It seems to me, that incrementing [] is the same like incrementing [[]][0] since first element of this outer array is [] indeed.

console.log(++[]);

console.log(++[[]][0]);

Upvotes: 4

Views: 108

Answers (2)

Quentin
Quentin

Reputation: 944075

++ increments and assigns a value.

You can assign a value to a variable or to a property of an object.

[] is neither. You can't say [] = [] + 1.

[[]][0] is the first item (property with the name 0) in the array (arrays are a type of object). You can say someArray[0] = [] + 1 (even though with ++[[]][0] the array is discarded as soon as the operation is complete).

Upvotes: 4

matvs
matvs

Reputation: 1873

Using an array literal in my example is actually quite confusing.
It gets much clearer when numbers are used.

According to increment operator definition:

The increment operator increments (adds one to) its operand and returns a value.

++4

Now it is at least for me more obvious that one cannot add one to numeric literal.

Upvotes: 0

Related Questions