This forum is now read-only. Please use our new forums at discuss.codecademy.com.

853 points
50e0e3ead3da9229ed000534 297062705
Submitted by
Matthew E. Everly
over 7 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?


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.

3117 points
Picture
Submitted by
Alex J
over 7 years ago

12 Comments

50e0e3ead3da9229ed000534 297062705 Matthew E. Everly over 7 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!

6eb506897bde430200bb99ec867492d0?s=140&d=retro boom_town over 7 years ago

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

5dceaff58a0231cc1e0a47726a88f680?s=140&d=retro Ardon Bailey over 7 years ago

Thanks for posting this!

5750255314f3ef016700022d 95834812 Palash almost 7 years ago

Good examples

5166e6ea72e22a0b26001e80 231656198 Frank Weird Techie almost 7 years ago

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

519926a08716f8368f00281d 675794965 missn over 6 years ago

Thank you for this!

298dfa9b711a5fd4607481df6324b31f?s=140&d=retro Scott Junner over 6 years ago

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

543825ef80ff33a7af00014a 475378528 Tonkec Palonkec about 6 years ago

Always enjoying reading your answers :) Great explanation :)

Picture Dean Allen almost 6 years ago

Very helpful! Will probably keep coming back to this.

5b42dbf8aa33d1dd350001ac 108269529 Ronan O'Brien over 5 years ago

champion explanation. Thanks so much for this!

A86f7a545bb298e9d17b1b0ba5ae2a31?s=140&d=retro Sergeant Shift almost 5 years ago

I echo Tonkec Palonkec

543825ef80ff33a7af00014a 475378528 Tonkec Palonkec almost 5 years ago

what?