Every statement must end with a semicolon;

The JavaScript interpreter is nice enough to add semicolons for us if we forget them. For most places this works, but then you get a bug that is impossible to fix, and the debugger doesn't give you the line number where the problem occurred because all your statements are mixed together.

// not so dangerous missing semicolon
function ReadFile(a){console.log(a)}
var filepath = "path-to-file"
var greeting = "Hello World"

Even though I have not included a single semicolon, my program runs just fine. The interpreter is smart enough to know where each statement ends and add the semicolons dynamically and correctly parse the code. However, there are times where the interpreter can fail and create chaos for you. Here is a bug that hunted me for days.

(function (){
    // do lots of awesome things
(function (){
    // then later do some more awesome things

And then when I check the log, it says the line number is on a line where there is absolutely no error. I had to do some major debugging to figure out what the problem was. If I had simply ended each statement with a semicolon, I would be a happier man. So here is the fix:

(function (){
    // do lots of awesome things
})(); // <--- yeah, the interpreter did not add this for me.
(function (){
    // then later do some more awesome things

Most people add semicolons when it is a value assignment statement like var a = "value";. The part where they fail is when the statement take multiple lines, like this one:

button.onclick = function () {
    // do lots and lots of stuff;
} // <-- A semicolon goes here

If it was written in a single line it would be more obvious:

button.onclick = function (){/*stuff*/};

So the lesson here is to say no thank you to the JavaScript interpreter and add your own semicolons at the end of each statement.

Note: Function declaration in the format function funcName(){} do not end with a semicolon.


There are no comments added yet.

Let's hear your thoughts

For my eyes only