Is null considered zero and undefined not a number on arithmetic expressions?

ε祈祈猫儿з 提交于 2019-11-29 09:17:06

Is null evaluated to 0 and undefined to NaN on arithmetic expressions? Is it safe or correct to assume this?

Yes, it is. An "arithmetic expression" would use the ToNumber operation:

 Argument Type | Result
 --------------+--------
 Undefined     | NaN
 Null          | +0
 …             |

It is used in the following "arithmetic" expressions:

It is not used by the equality operators, so null == 0 is false (and null !== 0 anyway)!

It seems safe to assume so since, in an arithmetic expression (e.g. addition), the method ToNumber would be called on it, evaluating NaN and +0 from undefined and null respectively:

                     To Number Conversions
╔═══════════════╦════════════════════════════════════════════╗
║ Argument Type ║                   Result                   ║
╠═══════════════╬════════════════════════════════════════════╣
║ Undefined     ║ NaN                                        ║
║               ║                                            ║
║ Null          ║ +0                                         ║
║               ║                                            ║
║ Boolean       ║ The result is 1 if the argument is true.   ║
║               ║ The result is +0 if the argument is false. ║
║               ║                                            ║
║ Number        ║ The result equals the input argument (no   ║
║               ║ conversion).                               ║
║               ║                                            ║
║ String        ║ See grammar and note below.                ║
║               ║                                            ║
║ Object        ║ Apply the following steps:                 ║
║               ║   1. Let primValue be ToPrimitive(input    ║
║               ║      argument, hint Number).               ║
║               ║   2. Return ToNumber(primValue).           ║
╚═══════════════╩════════════════════════════════════════════╝

ECMAScript Language Specification - ECMA-262 Edition 5.1

Without being type bound,

null == false == 0

null !== false !== 0

http://www.mapbender.org/JavaScript_pitfalls:_null,_false,_undefined,_NaN#0_6

With that said, null == 0, null + 4 = 4

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!