brianbolton.me

home

Semicolons protect you

30 Jan 2014

I’ve been wondering why some people put a semicolon at the end of their objects

var func = function(){
    console.log("hey3");
}; //semicolon

var func = function(){
    console.log("hey3");
} //no semicolon 

Both of these above statements define the function ‘func’ and nothing more. Lets see what happens when you forget it.

var func = function(){
    console.log("hey2");
}
//comments and whitespace here
(true);

This immediately defines func and then executes it. Whoops! Probably didn’t mean to do that. This can happen if you’re not careful OR if you are using a tool that combines your javascript code into one file.

var func = function(){
    console.log("hey3");
};//semicolon here protects you
(true);

This creates the function ‘func’ and the expression (true).

Here’s another scenario you might run into.

var x = {
    'func':function(){
        console.log("hey5")
    }
}
.func()

This immediately executes func and now x is undefined. Did you mean to do this?

var x = {
'func':function(){
    console.log("hey5")
    }
};
.func()

This is a syntax error. Probably a good thing.

View this fiddle for an interactive version of this code.