Why null + null = 0 in javascript

I did a test for fun when I noticed that null+null is 0 in javascript. Is there a reason for this?

+7
javascript null
source share
1 answer

The + operator only works with numbers and strings. When presenting something that is not a number or a string, it forces. The rules are covered by the specification , but the short version is that the operands are forcibly applied to primitives (which does not change anything in this particular case, null is primitive), and then, if either is a string, the other is forced to a string and concatenation is performed; if neither of them is a string, both are forced to numbers and the addition is performed.

So, null gets forced to a number that is 0, so you get 0+0 , which of course is 0 .


If anyone is interested in David Chaim null+[] is a "null" observation , this is due to this forced primitive thing that I mentioned: an empty array [] forced into the primitive. When you force an array to a primitive, it calls the toString() call, which calls join() . [].join() is "" because there are no elements. So this is null+"" . So, null forced into a string instead of a number, giving us "null"+"" , which of course is "null" .

+14
source share

All Articles