Why is not javascript "{} + []" equal to 0?

4

I was watching a video that was shown to me by the user @CiganoMorrisonMendez , called WAT .

There were some examples where they showed some bizarre things in some languages.

In particular what caught my attention was this line of JavaScript:

{} + [] // Resultado: 0

Adding a objeto with a array will return the value 0 . It may even seem clueless to this, but I want to know the explanation for this, since for this question there is also an explanation for the weirdness.

What is the reason for this behavior? I would like a step-by-step explanation of the above question.

    
asked by anonymous 16.05.2016 / 16:53

1 answer

4

These examples that generate curiosity have to do with the way with JavaScript uses the addition between different types. Nobody is surprised that 1 + 2 is 3 . But if we ask 3 + '4' already not everyone will be sure that JavaScript knows how to add Numbers and Strings.

What happens with {} + [] is that JavaScript tries to convert the types to try to solve the problem. What it does is read {} it ignores because it is a block empty, and then try to convert [] to a number. The + in JavaScript can be used as type-to-number converter, used a lot in +Date for example to convert date to timestamp or +'10 giving a number, 10. That is +[] is conversion from [] to Number, same as Number([]); that is 0 .

There is a good article on this here , with this example and others such as . Anyway, cases that are rarely used but can be fun to know.

    
16.05.2016 / 17:16