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");
}
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 ).
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.
🔗 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With