Question

I read a book about JS and can't understand next thing:

2 + null // => 2: addition after null converts to 0
2 + undefined // => NaN: addition after undefined converts to NaN

I read about how JS convert object to primitive values using toString() and valueOf(), but null and undefined don't have such methods - so how it works?

Was it helpful?

Solution

You can read this, for example: http://www.adequatelygood.com/Object-to-Primitive-Conversions-in-JavaScript.html

... However, the key mechanism that needs more explaining is the ToPrimitive function. This function is used to take an arbitrary value and get a corresponding primitive value instead. If the input is already a primitive value then the value will be returned without conversion. However, if the value is non-primitive, then it will call the internal [[DefaultValue]] method to find a default value for the object.

In short, it's internal mechanism.

OTHER TIPS

According to the ECMAScript specification at https://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1 It says when The Addition operator ( + ) is applied and the primitive values of given operands are not strings, both the operands are converted to primitive values, and then numeric value of those primitive values and add them. For example.

let x = 2 + null;

Here the 2 and null are both converted into Primitive values ie, 2(Number already primitive) and null (already primitive). And then converted to number with ToNumber function which gives values 2 and +0 for 2 and null respectively as per ToNumber. Now the values become

let x = 2 + (+0);

which become

let x = 2 + 0;

which become 2. Since the null and undefined are already primitive values. The [[DefaultValue]] isn't required here ie, not required to use valueOf since it is already a primitive value. The valueOf or toString are only required for values of Object type as mentioned in ToPrimitive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top