On a lot of browsers I've tested, JavaScript blocks actually return a value. You can test it out in any console:
for(var i = 0; i < 10; i++) {
var sqrt = Math.sqrt(i);
if(Math.floor(sqrt) === sqrt) {
i;
}
}
The "return" value is the last square number, that is, 9! But since it isn't an expression I suppose, you can't do this:
for(var i = 0; i < 10; i++) {
...
} + 5
That doesn't work. It gives + 5, or 5, of course, because it's a separate statement. Putting the loop in parentheses obviously fails, and if a block is in parentheses (e.g. ({f(); r}) - doesn't work) it's treated as an object and throws a syntax error.
One way to take advantage of the return value, as such, is to use eval:
eval('for(var i = 0; i < 10; i++) {var sqrt = Math.sqrt(i);if(Math.floor(sqrt) === sqrt) {i;}}') + 5; // 14
But I'm obviously not going to want to use that if eval is the only solution. Is there a way to use a block's resultant value without using eval that I'm missing? I really like this feature :)
eval's return value as the anomaly, not the restriction that JS "normally" (read: ignoring outsideeval) imposes. Blocks are not expressions.i;instead of what you think the for loop returns, assuming that in reality the for loop doesn't return anything).eval()returns the completion value of the JavaScript program that has been passed in as source text. This is an interesting point. Other than this, I am not aware of any other method to receive the completion value of a program/statement...