Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic semicolon insertion & return statements [duplicate]

As you might know, ECMAscript tries to be smart and will automatically insert semicolons if you didn't write those explicitly. Simple example

function foo() {
    var bar = 5

    return bar
}

will still work as expected. But there are some caveats if you rely on that. If we re-write that function like so

function foo() {
    var bar = 5

    return
    {
        bar: bar
    }
}

..that function would now return undefined because the interpreter would insert that semicolon right after the return statement (that's a reason why you always should bring curly brackets on the same line as a statement).

However, knowing all this I'm wondering now how safe a return statement like the following is, across browsers and versions

function foo() {
    var a = true,
        b = true,
        c = false;

    return a 
            && b
            && c;
}

I just wrote a similar return statement in a production environment. Just because I knew about the "problems" with ECMAscript beeing not-so-smart about semicolon insertion I'm wondering now, if that code works 100%. In my first tests on FF/Chrome/IE (latest versions) this seems to be totally fine, but is it really?

Does the automatic semicolon insertion "wake-up" if there is anything else but the return statement in that line? Can anyone provide implementation-level detail about this?

like image 251
jAndy Avatar asked Oct 05 '12 11:10

jAndy


1 Answers

The javascript interpreter/compiler is so smart to only insert automatic semicolons if afterwards there is valid Javascript.

Your code works, because && b as it stands is no valid expression - that's why no semicolon gets inserted after the return a resulting in:

return a && b && c;

However:

return (undefined);//implicitely inserted
{
    ....
}

is perfectly valid and thats why a semicolon gets inserted.

For completeness' sake the ref to the spec: automatic semicolon insertion. THe examples are worth reading through.

like image 196
Christoph Avatar answered Oct 08 '22 21:10

Christoph