Profile image of MatthewEE
Submitted by MatthewEE
over 12 years

When (not) to use semicolons

I know this isn’t a precise question about the exercise, but it’s something I often become confused about. This particular exercise helped me see the question I have-

This brings me to syntax.
The other exercises explain the functions, and the math involved, but overlook explaining why there’s a semicolon behind the curly bracket in some places, and others there isn’t. Also behind some functions within curly brackets, a semicolon is considered “unnecessary” and others is required.

A few examples-

SEMICOLON NEEDED

var cube = function(n) {  
    return n*n*n;
};

NONE NEEDED

if (i % 15 === 0) {
    console.log("FizzBuzz");
}

Can anyone explain just a bit, to help ease my curious mind and help me prevent simple errors in the future?

Answer 508000efde2d860200004bbe

52 votes

Permalink

The semicolon in JavaScript is used to separate statements, but it can be omitted if the statement is followed by a line break (or there’s only one statement in a {block}). A statement is a piece of code that tells the computer to do something. Here are the most common types of statements:

var i;                        // variable declaration
i = 5;                        // value assignment
i = i + 1;                    // value assignment
i++;                          // same as above
var x = 9;                    // declaration & assignment
var fun = function() {...};   // var decl., assignmt, and func. defin.
alert("hi");                  // function call

All of these statements can end with a ; but none of them must. The semicolon is only obligatory when you have two or more statements on the same line:

var i = 0; i++        // <-- semicolon obligatory
                      //     (but optional before newline)
var i = 0             // <-- semicolon optional
    i++               // <-- semicolon optional

You shouldn’t put a semicolon after a closing curly bracket }. The only exceptions are assignment statements, such as var obj = {};, see above.

// NO semicolons after }:
if  (...) {...} else {...}
for (...) {...}
while (...) {...}

// BUT:
do {...} while (...);

// function statement: 
function (arg) { /*do this*/ } // NO semicolon after }

It won’t harm to put a semicolon after the { } of an if statement (it will be ignored, and you might see a warning that it’s unnecessary). But a semicolon where it doesn’t belong (such as after the round (brackets) of an if, for, while, or switch statement) is a very bad idea:

if (0 === 1); { alert("hi") }

// equivalent to:

if (0 === 1) /*do nothing*/ ;
alert ("hi");

This code will alert “hi”, but not because 0 equals 1, but because of the semicolon. It makes JavaScript think that you have an empty statement there, and everything to the right of it is treated as no longer belonging to the if conditional and thus independent of it.

[edit] Another important quirk: inside the () of a for loop, semicolons only go after the first and second statement, never after the third:

for (var i=0; i < 10; i++)  {/*actions*/}       // correct
for (var i=0; i < 10; i++;) {/*actions*/}       // SyntaxError

The JavaScript syntax proofing tool JSLint, which is built into the Codecademy code editor, does a pretty good job of finding unnecessary semicolons – or missing ones. It’ll show you yellow warning triangles in code lines. Hovering the mouse over a triangle will tell you if there’s a missing semicolon or an unnecessary one. You can generally trust those warnings until you develop an intuition of where to use semicolons and where not to.

Some consider it a good habit to terminate each statement with a ; – that makes your code a little easier to parse, and to compress: if you remove line breaks you needn’t worry about several statements ending up unseparated on the same line.

Profile image of fanaugen
Submitted by fanaugen
over 12 years

12 comments

Profile image of MatthewEE
Submitted by MatthewEE
over 12 years

This is exactly what I needed, and I can’t thank you enough. It makes sense, and helps my mind decipher what I’m doing! I really can’t say enough good things about my experience here so far. Helpful mods, and a wonderful tool for curious minds. Keep up the good work!

Profile image of boom_town
Submitted by boom_town
over 12 years

I agree, that’s helped my understanding hugely! Thanks for the question and answer!

Profile image of Waymond
Submitted by Waymond
over 12 years

Thanks for posting this!

Profile image of dFireGod
Submitted by dFireGod
about 12 years

Good examples

Profile image of blogSolver02332
Submitted by blogSolver02332
about 12 years

Now this goes a long way to solving my little problem. Thanks for this!!!

Profile image of missn
Submitted by missn
about 12 years

Thank you for this!

Profile image of HologramOfMe
Submitted by HologramOfMe
almost 12 years

Think I’ll have to refer to this a few times more. Great info.

Profile image of TonkecPalonkec
Submitted by TonkecPalonkec
over 11 years

Always enjoying reading your answers :) Great explanation :)

Profile image of anonymous
Submitted by anonymous
about 11 years

Very helpful! Will probably keep coming back to this.

Profile image of someblokeinasuit
Submitted by someblokeinasuit
almost 11 years

champion explanation. Thanks so much for this!

Profile image of anonymous
Submitted by anonymous
about 10 years

I echo Tonkec Palonkec

Profile image of TonkecPalonkec
Submitted by TonkecPalonkec
about 10 years

what?