Skip to Content
Delete Icon
This forum is now read-only. Please use our new forums at discuss.codecademy.com.
0 points
Submitted by Matthew E. Everly
8 years ago

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.

alt

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.

3117 points
Submitted by Alex J
8 years ago

12 comments

Matthew E. Everly 8 years ago

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!

boom_town 8 years ago

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

Ardon Bailey 8 years ago

Thanks for posting this!

Palash 8 years ago

Good examples

Frank Weird Techie 8 years ago

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

missn 8 years ago

Thank you for this!

Scott Junner 7 years ago

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

Tonkec Palonkec 7 years ago

Always enjoying reading your answers :) Great explanation :)

Dean Allen 7 years ago

Very helpful! Will probably keep coming back to this.

Ronan O'Brien 6 years ago

champion explanation. Thanks so much for this!

Sergeant Shift 6 years ago

I echo Tonkec Palonkec

Tonkec Palonkec 6 years ago

what?