Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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??

like image 286
Joe Avatar asked Aug 03 '11 22:08

Joe


People also ask

What is at the end of a line of code in JavaScript?

The semi-colon, ; , in JavaScript represents an “end of statement” or “statement delimiter”. It tells JavaScript not to parse any more code, and to go ahead and execute the statement up to that point. JS does everything top down, left to right, one statement at a time.

Does JavaScript have to end with semicolon?

Semicolons are not required for JavaScript programming, nevertheless I advice you to use it. It makes your code more readable and is actually a good practice, and almost all cool programming languages uses it. Take a stand and use it, it's up to you now!

What is required to end a line of code?

In a lot of the C based languages such as C#, Java and C++, a semicolon is required to end the line.


2 Answers

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.

like image 130
riwalk Avatar answered Nov 10 '22 06:11

riwalk


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.

like image 37
Razor Storm Avatar answered Nov 10 '22 08:11

Razor Storm