Javascript Blockstatement Confusion
Solution 1:
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.
Post a Comment for "Javascript Blockstatement Confusion"