Search code examples
javascriptprimitive

Object to primitive conversions in JavaScript


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?


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.