Putting ; at the end of a function definition

javascript, jslint

Solution

TL;DR: Without a semicolon, your function expression can turn into an Immediately Invoked Functional Expression depending on the code that follows it.

Automatic semicolon insertion is a pain. You shouldn't rely on it:

var tony = function () {
   console.log("hello there"); // Hint: this doesn't get executed;
};
(function() {
  /* do nothing */
}());

Versus:

var tony = function () {
   console.log("hello there"); // Hint: this gets executed
}
(function() {
  /* do nothing */
}());

In the second (bad) example, the semicolon doesn't get inserted because the code that follows it can make sense. So the anonymous function you expected to be assigned to tony gets called instantly with some other stuff as argument and `tony` gets assigned to the return value of what you expected to be `tony`, which is really not what you wanted.

Problem

Why is it considered best practise to put a ; at the end of a function definition. e.g. ``` var tony = function () { console.log("hello there"); }; ``` is better than: ``` var tony = function () { console.log("hello there"); } ```

Original source