Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting ; at the end of a function definition

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");
}
like image 346
More Than Five Avatar asked Nov 18 '13 12:11

More Than Five


People also ask

What does Const do at the end of a function mean?

const at the end of the function means it isn't going to modify the state of the object it is called up on ( i.e., this ).

What does def () mean in Python?

def is the keyword for defining a function. The function name is followed by parameter(s) in (). The colon : signals the start of the function body, which is marked by indentation. Inside the function body, the return statement determines the value to be returned.

What are the different parts of a function definition?

🔗 A function has three parts, a set of inputs, a set of outputs, and a rule that relates the elements of the set of inputs to the elements of the set of outputs in such a way that each input is assigned exactly one output.

What happens if you define a function but do not call it?

A common error is defining a function but forgetting to call the function. A function does not automatically get executed. A function that does not explicitly return a value returns the JavaScript value undefined.


1 Answers

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.

like image 182
Tibos Avatar answered Sep 29 '22 07:09

Tibos