JavaScript Adding Booleans

后端 未结 3 598
眼角桃花
眼角桃花 2020-12-10 02:23
console.log(true+true); //2
console.log(typeof(true+true)); //number
console.log(isNaN(true+true)); //false

Why is adding together 2 boolean types

3条回答
  •  -上瘾入骨i
    2020-12-10 02:39

    It works like that because that's how it's specified to work.

    EcmaScript standard specifies that unless either of the arguments is a string, the + operator is assumed to mean numeric addition and not string concatenation. Conversion to numeric values is explicitly mentioned:

    Return the result of applying the addition operation to ToNumber( lprim) and ToNumber(rprim).

    (where lprim and rprim are the primitive forms of the left-hand and the right-hand argument, respectively)

    EcmaScript also specifies the To Number conversion for booleans clearly:

    The result is 1 if the argument is true. The result is +0 if the argument is false.

    Hence, true + true effectively means 1 + 1, or 2.

提交回复
热议问题