开发者

does javascript require ';' at the end of a line of code?

开发者 https://www.devze.com 2023-03-24 21:45 出处:网络
I have seen and used javascript code that both has and omits the \';\' from the end of statements. Are they required in some cases and not in others? If so can you give some examples, and if not what

I have seen and used javascript code that both has and omits the ';' from the end of statements. Are they required in some cases and not in others? If so can you give some examples, and if not what is the general standard, to use the ';' or to not...that..is the question?开发者_JS百科?


JavaScript uses a (generally disliked) method called Semicolon Insertion, where it will allow you to omit semicolons.

The rules for where you can and cannot insert semicolons is extensive, and covered fairly well here.

In general, do not rely on semicolon insertion. It is a poorly thought out feature and will hurt you before it helps you.

Not only should you always use semicolons, but you should also get in the habit of putting your { braces on the same line, as semicolon insertion can actually misinterpret what you meant.

For example, say I'm trying to return a javascript object from a function:

function f() {
    return { "a":"b", "c":"d" }    // works fine
}

function g() {
    return                         // wrong!!!
    {
        "a":"b",
        "c":"d"
    }
}

If I put the { on a new line (as I did in g), the return statement will actually have a semicolon inserted after it, destroying the meaning of what you were saying.

Overall, semicolon insertion is a poor feature and you should never rely on it.


Use ; to mark the end of a statement. Javascript follows the syntactical theme set in C family languages, and ; is the delimiter for the end of a statement.

What code have you seen that omits this?

If there's no more code in the block after a line, the ; is technically optional. You should include it anyway.


Always use the semicolon, this makes the code easier to read. Right now I am not aware of any situation where it can be omitted.

0

精彩评论

暂无评论...
验证码 换一张
取 消