I am trying to understand the core of JavaScript. I know it doesnt have much implementation value. If you dont want to answer, just leave it. However, I will appreciate if you could help to understand the following type coercion while applying addition(+).
1.
null + null // 0
2.
null + undefined; // NaN
3.
null + NaN; // NaN
4.
1 + null; //1
5.
true + null; //1
6.
true + [null]; //"true"
I know null is an empty or missing object. I will appreciate, if you can explain steps in type coercion or unary(+) operation here. Thanks for reading the question.
This is covered in 11.6.1 The Addition operator ( + ) - feel free to read it and follow the rules.
The first five cases can be explained by looking at
ToNumber
:And
0 + 0 == 0
(and1 + 0 == 1
), whilex + NaN
orNaN + x
evaluates to NaN. Since every value above is also a primitive,ToPrimitive(x)
evaluates to x (where x is not a string) and the "string concatenation clause" was not invoked.The final case is different in that it results from the
ToPrimitive
(which ends up callingArray.prototype.toString
) on the array which results in a string value. Thus it ends up applyingToString
, notToNumber
, and follows as such:Conclusions derived from analysing results
true
coerces to 1 (andfalse
to 0).null
coerces to 0.undefined
coerces to NaN.Arrays behave as:
+[]
):1+[]
):All operations on NaN return NaN