JavaScript BlockStatement confusion

前端 未结 1 1077
忘了有多久
忘了有多久 2020-12-10 18:35
{1 + \'\'} + 10 // 10
{1 + \'\'} + \'\' // 0

Why does this happen? Do BlockStatements return 0, and why?

相关标签:
1条回答
  • 2020-12-10 19:20

    Do BlockStatements return 0...?

    No, blocks return the value of the last expression within them. You can see this by just doing:

    {1 + 8}
    

    ...in the JavaScript console, which will show 9.

    {1 + ''} + 10 // 10
    {1 + ''} + '' // 0
    Why does this happen?

    Because although the block does return a value, that value is not used. {1 + ''} + 10 // 10 code is evaluated as two distinct items:

    {1 + ''} // "1"
    +10      // 10
    

    ...or writing those with standard indentation and semicolons:

    {
        1 + '';
    }
    +10;
    

    ...and you're seeing the result of the second one, as though the first one weren't there at all. The + there isn't the addition operator, it's the unary + (similar to the unary -, but it doesn't change the sign of its operand). +10 is, of course, 10; and +'' is 0 because applying the operator to a string converts the string to a number, and Number('') is 0.

    You can prove that you're seeing the unary + rather than the addition operator by trying this:

    {1 + ''} * 10
    

    ...which is really

    {
        1 + '';
    }
    *10;
    

    It fails with a syntax error because there is no unary *.

    As Felix kindly points out in the comments below, for the + in your example to be the addition operator (which would have ended up concatenating strings, in your case), it would have to be between two expressions, and a block is a statement, not an expression.

    0 讨论(0)
提交回复
热议问题