what it will print console.log(1+ + “2”)

前端 未结 3 1391
名媛妹妹
名媛妹妹 2021-01-16 22:53

Why does this JavaScript statement:

console.log(1 +  + \"2\");

print

3

as the output? I am not sure why

相关标签:
3条回答
  • 2021-01-16 23:18

    console.log(1 + "2") prints 12 as + acts as an concatenation operator.

    But if you try to print console.log( + "2" ) you will get output as 2 coz it is casted as an integer.

    Therefore console.log( 1 + +"2" ) will give you result as 3

    0 讨论(0)
  • 2021-01-16 23:18

    Regarding the specific output of

    console.log(1 +  + "2");
    

    Run it on your browser console. The better question is why does it output what it does -

    console.log(1 +  + "2");
                  ^
    

    That is the binary + operator, which will concatenate strings or add numbers.

    console.log(1 +  + "2");
                     ^
    

    That one is the unary + operator, which converts "2" to a number.

    Don't create JavaScript like this. It's confusing.

    0 讨论(0)
  • 2021-01-16 23:21

    + or - operand in front of a string converts it to number. so here +"2" will become 2 hence the result will be 3.

    => 1 + + "2"    // +"2" = 2
    => 1 +    2
    => 3
    

    If you use - in between like

    => 1 - - "2"   // -"2" = -2
    => 1 - - 2     // 1 - (-2)
    => 1 + 2
    => 3
    

    So,

         -"2" ==> -2
         +"2" ==>  2
     +"Hello" ==> NaN
     -"Hello" ==> NaN
    
    0 讨论(0)
提交回复
热议问题