Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 592
AnonBird Avatar asked Sep 04 '16 09:09

AnonBird


1 Answers

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 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, which is 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".

like image 106
T.J. Crowder Avatar answered Oct 07 '22 15:10

T.J. Crowder