Semi-colons !? I don't quitte understand them?


#1

I need help to understand exactly where you need semi-colons and where you don't.. I know it's to end a line , but that's not clear enough. It's the thing that makes most of the bugs in my codes.. for example:

this way instead of counting "1,2,3,4,5".. it printed out "6".;

for(var f=1;f<6;f++); {
console.log(f);
}

But when I removed the semi-colon after the for(condition), then it all worked perfectly..;

for(var f=1;f<6;f++) {
console.log(f);
}

And if you notice, it's such a small details that it makes debugging kinda long and troublesome !! thanks for your help.


#2

I am pretty sure it's at the end of any line UNLESS that line has a {. Can't think of any other exceptions.


#3

someone wrote a nice article about this, you can find it here.

why do you think programming is not for everyone. Debugging can be so frustrating, people who think programming is easy are so wrong!! it can be frustrating, you have to think in multiply language, bugs are easy made, and way harder to find.

@bruce_wiseman, not entirely true, if you have a function, you need a semi-colon after the closing curly bracket:

var setName = function(name = “John Doe”) {  
  return name;
};

or if i have an object:

var car = {type:"Fiat", model:500, color:"white"};

#4

Well I'll give you a few examples of when to and when not to do it. But general rule of thumb is that you do not put a semi-colon at the end of a line if the line ends with an opening bracket " { ".

console.log("..."); //<--

var example = "..."; //<--

var Example1(parameter){ ... }; //<---

function Example2(parameter){ ... } //Nope

var EXA = { //Nope
    MPLE: 3, //<-- Comma
    MPLE: 4 //Nothing
}; //<--- there we go!

There are many rules as to when you can place a semi-colon. If you want a more in depth answer you can google it :smiley:


#5

I now realise I wasn't really clear with saying that any line that ends in a {.


#6

Wow that was super fast for answers ! Thanks a lot. That aricle stetim94 gave me is perfect ! Although semi-colons are still kinda complicated..


#7

I guess here is a = function missing :smile:

Yet another rule of thumb would be a semicolon after every function call such as console.log(...); and after every line with an assignment or declaration e.g.

    var name = value;
    name = value;

And if you are still confused about why it prints 6 instead of 1,2,3,4,5 with the semicolon at that place you might have a look at this post:


It's about conditions but the next statement rule applies to the loops as well.