16

I was doing some test for fun when noticed null+null is equal to 0in javascript. Is there any reason for it ?

4
  • 2
    Operands of the + operator are casted to numbers, unless they aren't strings Commented Sep 4, 2016 at 9:03
  • 1
    @hindmost not always, but close enough Commented Sep 4, 2016 at 9:04
  • @hindmost null+[] is actually "null". I'd say it's pretty much standarized arbitrarly Commented Sep 4, 2016 at 9:05
  • 1
    Closely related: stackoverflow.com/questions/9032856/… Commented Sep 4, 2016 at 9:09

1 Answer 1

26

The + operator works only with numbers and strings. When presented with something that isn't a number or a string, it coerces. The rules are covered by the spec, but the short version is that the operands are coerced to primitives (which changes nothing in this particular case, null is a primitive) and then if either is a string, the other is coerced to string and concatenation is done; if neither is a string, both are coerced to numbers and addition is done.

So null gets coerced to a number. The specification dictates that null becomes 0, so you get 0+0 which is of course 0.


If anyone's curious about David Haim's null+[] is "null" observation, that happens because of that coercion-to-primitive thing I mentioned: The empty array [] is coerced to a primitive. When you coerce an array to a primitive, it ends up calling toString(), which calls join(). [].join() is "" because there are no elements. So it's null+"". So null is coerced to string instead of number, giving us "null"+"" which is of course "null".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.