Are semicolons mandatory for javascript statements?

I want to know if this is legal?

function test() { alert ("hello") $("#loading").show(); } 

Or should I write this instead:

 function test() { alert ("hello"); $("#loading").show(); } 

Are semicolons optional in JavaScript? Because I saw this on the forum:

No, semicolons are generally not required for JavaScript (Google to automatically set semicolons). Using them, the code looks much cleaner, and ASI is a terrible wrong function (at least in my opinion).

+7
source share
2 answers

Semicolons are not always required, but I always recommend using them. See the ECMAScript specification for automatic semicolon rules:

Some ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must end with a semicolon. Such semicolons can always be displayed explicitly in the source text. However, for convenience, such semicolons may be omitted from the source text in certain situations. Describing these situations, saying that semicolons are automatically inserted into the source code token stream in these situations.

Refresh (for further explanation)

Perhaps the most common situation used to show why automatically inserting a semicolon can be bad is what was touched by @sissonb in another answer. Consider the following:

 function something(a, b) { return a + b; } 

What you expect is to ignore the new line, and the code is interpreted as:

 function something(a, b) { return a + b; } 

Unfortunately, automatic semicolon insertion comes into play, and the code is actually interpreted as follows:

 function something(a, b) { return; a + b; } 

And an empty return means that the function returns undefined . So, instead of the good sum of the two arguments, you get undefined and may end up being very confused about where you went wrong! That's why I completely agree with the statement in your question that automatic semicolon is a terrible mistake.

+12
source

Semicolons are optional. They are automatically added at the end of the line if they are missing, which actually causes this code to return undefined.

 return { text:"hello" } 
0
source

All Articles