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

- 570
- 13
- 27
-
2Operands of the `+` operator are casted to numbers, unless they aren't strings – hindmost Sep 04 '16 at 09:03
-
1@hindmost not always, but close enough – tereško Sep 04 '16 at 09:04
-
@hindmost null+[] is actually "null". I'd say it's pretty much standarized arbitrarly – David Haim Sep 04 '16 at 09:05
-
1Closely related: http://stackoverflow.com/questions/9032856/what-is-the-explanation-for-these-bizarre-javascript-behaviours-mentioned-in-the – T.J. Crowder Sep 04 '16 at 09:09
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"
.

- 1
- 1

- 1,031,962
- 187
- 1,923
- 1,875