Hacker News new | ask | show | jobs
by slurpme 6686 days ago
How about this surprise which caught me out a couple of days ago, try:

function hello () {

    return
    {
       value : 10
    };
}

window.alert (hello ().value);

It burps in FF and IE...

1 comments

This happens when putting a newline between return and any value.

This is actually a result of JavaScript's lax support of semi-colons. Semi-colons are generally not enforced in JavaScript, but this leads to some ambiguous cases. Your case may not seem ambiguous, but the following code snippet will show what is actually going on:

if (i==5) return

i += 3;

As you can see, there are 2 possible meanings for this when there is no explicit semi-colon after the return. It can either mean "if i equals 5 return, else add 3 to i" or it could mean, "if i equals 5 return i plus 3". JavaScript does not try to discern which is "more correct" (since there are no return types on functions so this would be a very difficult task), but rather defaults to "floating returns" meaning "return;".

I know, I mentioned it as the new object because it's one of the few situations I know of where you might use a newline after the return keyword.

I understand what you mean, in this case though it would be helpful if the interpreter detects the statement as being not reachable since it's after the return.