Javascript Compiler behavior - double plus for array of empty array and array of zero is.. ONE

javascript

Solution

This is best explored by breaking down the way its components evaluate.

`[[]][0]` alone evaluates to the empty array `[]`. By adding `+` in front, you cast its string representation to an integer 0 (like saying `+4` or `-3`) via a unary positive operator. `+0` is just `0`.

`++` as a numeric operator, also casts the empty string to an integer `0`, but applies its operation (the prefix increment) resulting `1`.

[[]][0]
// [] empty array
[[]][0].toString()
// ""

// Unary + casts the empty string to an integer
+("")
// 0

// Prefix increment on an empty string results in 1 (increments the 0)
var emptyString = "";
++emptyString;
// 1

Problem

My question may be already answered, but I could not find it not in Search Engines google or bing doesn't like '+' (plus) sign in search request. Anyway, why this is zero ``` +[[]][0] // = 0 ``` and this is one ``` ++[[]][0] // = 1 ``` UPD: Michael Berkowski have a good answer, but I steal don't understand one thing if `[[]][0]` evaluates to an empty array, then why `++[]` is `ReferenceError: Invalid left-hand side expression in prefix operation` UPD2: now I get it.. it seems I was trying to type ++0 in console and getting an Error, but I should be using var a = 0; ++a

Original source

Related problems