javascript – Why is _=$=+[],++_+''+$ equal to 10?

Question:

While reading I found this expression:

_=$=+[],++_+''+$

Curiously, it is a valid expression in javascript , but the most curious thing is that when it is executed, the result is:

10

I tried to make sense of it by breaking the expression down but I didn't get much done.

Why is the result of that expression equal to 10 ?

Answer:

Easy, this expression

_=$=+[],++_+''+$

It can be written more readably like this

_ = $ = +[], ++_ + '' + $

Which can be understood as:

(_ = $ = +[]), (++_ + '' + $)

Which is the same as:

_ = $ = +[];
++_ + '' + $;

Which is the same as:

$ = +[];
_ = $;
++_ + '' + $;

That to read it easier we can rename variables like:

var1 = +[];                 // +[] fuerza al empty array a volverse number 0
var2 = var1;                // Ahora var1 y var2 valen 0
++var2 + '' + var1;         // ++var2 === 1, 1 + '' === '1' y '1' + 0 === '10'

Than executing it step by step:

var1 = 0;
var2 = var1;              
++var2 + '' + var1  
...
var2 = 0;              
++var2 + '' + var1;
...
++var2 + '' + 0;       //var2 === 0
...
1 + '' + 0;
...
'1' + 0;
...
'10';
Scroll to Top