-->

Does a semi-colon matter in JavaScript [duplicate]

2019-01-29 10:41发布

问题:

Possible Duplicates:
do we need semicolon at the end
Why use semicolon?
Are semicolons needed after an object literal assignment in JavaScript?
Should I use semicolons in JavaScript?
should I use semicolon at end of line when coding JavaScript?
Enforce semicolons in my Javascript?
What are the rules for JavaScript's automatic semicolon insertion (ASI)?
I've heard Javascript inserts ";" automatically and that may cause problems
Do you recommend using semicolons after every statement in JavaScript?
Why should I use a semicolon after every function in javascript?
Why is a semicolon required at end of line?

This was a strange issue I faced once I was coding.

Consider the following:

function foo()
{
alert("This does not have a semi-colon and works in Chrome but not in IE")
}

and

function foo1()
{
alert("This has a semi-colon and works everywhere");
}

Why does this happen?

回答1:

If you don't put a semicolon at the end of the line, one will be added for you when your code runs.
However, it's very recommended to put the semicolons yourself, otherwise your code might not behave the way you expect it to.
For more info about this, i recommend you look up "Javascript - the good parts"
consider this example of why it's problematic.



回答2:

Semicolons help in readability, especially if you use lots of whitespace and indents to make your code neater.



回答3:

Semicolons act as a terminator of an expression or statement. It informs the script interpreter that the current expression or statement is done and to start with the next.