Search code examples
javascriptundefinednul

Why undefined plus undefined equals to Nan in Javascript


How to understand undefined and null much better

console.log(undefined + 5) //NaN

console.log(null + 5) //5

console.log(undefined + undefined) //NaN


Solution

  • + operator applies an implicit coercion to an integer to an operand when the other is a number

    undefined is coerced to NaN, so console.log(undefined + 5) and console.log(undefined + undefined) output NaN

    null is coerced to number 0, so console.log(null + 5) is equivalent to console.log(0 + 5). Therefore 5 is outputted