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

后端 未结 3 1561
离开以前
离开以前 2020-12-17 10:45

Is null evaluated to 0 and undefined to NaN on arithmetic expressions?

According to some testing it seems so:

3条回答
  •  执念已碎
    2020-12-17 11:02

    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:

    • prefix/postfix increment and decrement
    • the unary + and - operators
    • the + operator if none of the two arguments is a string
    • subtraction, multiplication, division and modulo operation
    • relational operators if not both arguments are strings

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

提交回复
热议问题