Is semicolon at the beginning of code still good practice?
The more common practise is to add a semicolon at the end of the file. The issue is, when you concatenate two files like this:
// file1.js
(function() {
})()
// file2.js
(function() {
})()
Without putting a semicolon at the end of file1
, it will try to invoke the return value from the function in file1
with the function in file2
.
Putting a semicolon at the end of each file will solve this (as will putting them at the beginning).
Another way is to turn the function invocation into a statement like this:
!function() {
}();
I think this is also recommended by JSLint, because in this case you don't have to worry about semicolons (although you should use them anyway but that's a different discussion altogether ;).
Ideally minifying and merging multiple files should have no affect your coding style. You should be able to write your program as you wish and then use an automated tool to correctly merge and minify your project.
There are lots of automated tools that do this. Take a look at UglifyJS 2 for example. I'm sure you'll be able to find many more such tools if you look around.
Getting back to the question, it's important to insert a semicolon after an immediately invoked function expression as Daff pointed out. However there's no reason to put a semicolon before it. If you be a good boy and put a semicolon after every statement and expression then you should never have any problems.
Do not let JavaScript ever do automatic semicolon insertion for you.
The only place where it's permissible to not put a semicolon is after a function declaration:
function foo() {} // it's alright to not put a semicolon here
However if you're using a function expression then always put a semicolon.
(function foo() {})(); // you should put a semicolon here
Putting semicolons anywhere else is just confusing. Especially at the beginning of a line. People from other programming backgrounds may also think it's the start of an end of line comment.