Why does javascript "{} + []" equal 0?

Asked

Viewed 214 times

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 present in some languages.

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

{} + [] // Resultado: 0

By adding a objeto with a array the value 0 is returned. It may even seem unaware this, but I want to know the explanation for this, since for this question there’s also an explanation for the weirdness.

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

  • 3

    Empty = False, False = 0, 0 + 0 = 0.

1 answer

4


These curious examples have to do with the way Javascript uses the addition between different types. No one is surprised that 1 + 2 be it 3. But if we ask 3 + '4' not everyone will be sure that Javascript knows how to add Numbers and Strings.

What happens to {} + [] is that Javascript tries to convert types to try to solve the problem. What it does is read {} he ignores for being a block empty, and then will try to convert [] in a number. The + Javascript can be used as Type to Number converter, use-of much in +Date for example to convert the date to timestamp or +'10 that gives a Number, 10. That is to say +[] is the conversion of [] in Number, the same as Number([]); that is 0.

There’s a good article about it here, with this example and others that such. Anyway, cases that are rarely used but that can be funny to know.

  • Interesting last explanation on Number([]), because I noticed that the same happens with the operator - (subtraction)

  • As cited article, it uses examples via console.log, but should be run directly on V8, or use the function eval({}+[]) in this case returns 0, but if do {}+{} returns "[Object Object][Object Object]" and with eval('{}+{}'); returns NaN

  • @David because in Node.js gives some different results that in the implementation of browsers/console.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.