Search code examples
javascriptnull

Why is null+null = 0 in javascript


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


Solution

  • 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".