Skip to content

Latest commit

 

History

History
31 lines (25 loc) · 2.86 KB

;.md

File metadata and controls

31 lines (25 loc) · 2.86 KB

Automatic Semicolon Insertion (ASI)

There are two schools of thought as to whether to include semicolons at the end of your statements. To always use them to terminate statements, or to never use them unless there is an ambiguity. Of course, this is the rare case where neither schools are wrong, and it is the language it self that is wrong in the first place. Yes. I admit it. No matter how many excuses I may provide for its other "features" as I call them, Automatic Semicolon Insertion may have been the next worst thing after Java. You see, no matter which preference you subscribe to, you will still be at the mercy of Javascript's ASI rules. Choosing to pretend that it does not exist and naively inserting newlines wherever you fancy to beautify your code and then plopping down a dot comma when you think you're done is wishful thinking. The following example is taken right from the ECMAScript specifications:

//The source
return
a + b
//is transformed by automatic semicolon insertion into the following:
return;
a + b;

So, if the rule "put semicolons whereever you intend to end your statements" is used, and you wrote:

function returnObject() {
    return 
    {
        prop: 'value'
    };
}

The code would still not conform to your expectations, as the Javascript parser will so graciously attempt to "correct" your invalid Javascript, and help you squeeze a semicolon after the return, and thus the function will return undefined.

You would still need to learn where Javascript will automatically insert semicolons anyway, as this feature is unturnoffable. But telling beginners to Javascript "Please put semicolons at the end of your statements" does not educate them on what exactly is defined as a statement in Javascript, and where Javascript allows you to break up your code into multiple lines and still be considered a valid statement instead of prematurely terminating them for you.

If you are a beginner, what do I suggest?

Please never use semicolons when starting off learning Javascript. Semicolons provide a false sense of security especially when coming from other semicolon-mandatory languages like Java and C. They will helpfully throw you an error if you break up a line at the wrong place at the wrong time. But not Javascript.

You remember what I said about == and != doing funny stuff by converting your stuff here and there trying to make them equal and then telling you if they are equal? You don't have to know any of that. You just don't use == and != and that's the end of the story. Your sanity is preserved. But you can't not use ASI in Javascript. There is no option to turn it off. Whether you like it or not, Javascript will put semicolons as it sees fit. So unfortunately you have to learn the rules of ASI.

They're not that hard to master