13

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");
}
More Than Five
  • 9,959
  • 21
  • 77
  • 127
  • Both seems to be the same .. First says that your statement has been ended .. Second doesn't – Prasath K Nov 18 '13 at 12:44
  • I'm not sure but JavaScript add automaticly a semicolon. So it's a "defensive semicolon". http://en.wikipedia.org/wiki/JavaScript_syntax#Whitespace_and_semicolons – Franck Nov 18 '13 at 12:47
  • Well, for me it is a way to force editor to realign function code – FLCL Nov 18 '13 at 12:47

2 Answers2

35

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.

Tibos
  • 27,507
  • 4
  • 50
  • 64
8

You posted a function expression. Unlike blocks, statements are terminated with semicolons so you should insert a semicolon there instead of relying on ASI to do it for you implicitly.

Not adding the semicolon can result in unexpected behaviour depending on the code that follows.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636