Search code examples
javascripttypesnantypeof

Javascript why console.log(typeof "Not a Number" - "Number") prints 'NaN'?


I know and acknowledge that

console.log(typeof NaN) // 'number'

however I need help understanding the logic of

console.log(typeof "Not a Number" - "Number") // 'NaN'

Looking at this

console.log("NaN is normal" - "normal" + "special") // NaNspecial

I see that "NaN is normal" - "normal" gives NaN (which is a number type) which then get's converted to a string before concatenation.


Solution

  • See operator precedence. typeof has a precedence of 17, and subtraction has a precedence of 14. So

    console.log(typeof "Not a Number" - "Number") // 'NaN'
    

    is equivalent to:

    console.log(typeof "Not a Number" - "Number") // original line
    console.log((typeof "Not a Number") - "Number") // grouping; operator precedence
    console.log(("string") - "Number")
    console.log("string" - "Number")
    // A string can't be meaningfully subtracted from another string, so the result is NaN
    console.log(NaN)
    

    Similarly, - and + have the same precedence, and work left-to-right, so the final code is equivalent to:

    console.log("NaN is normal" - "normal" + "special") // original line
    console.log(("NaN is normal" - "normal") + "special")
    console.log((NaN) + "special")
    // NaN gets coerced to a string and concatenated:
    console.log("NaNspecial")