{1 + ''} + 10 // 10
{1 + ''} + '' // 0
Why does this happen? Do BlockStatements return 0, and why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, blocks return the value of the last expression within them. You can see this by just doing:
…in the JavaScript console, which will show
9.Because although the block does return a value, that value is not used.
{1 + ''} + 10 // 10code is evaluated as two distinct items:…or writing those with standard indentation and semicolons:
…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).+10is, of course,10; and+''is0because applying the operator to a string converts the string to a number, andNumber('')is0.You can prove that you’re seeing the unary
+rather than the addition operator by trying this:…which is really
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.