简体   繁体   中英

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM