I am reading this book and it has this code example
function getFunction() {
var result = [];
for (var i = 0; i < 10; i++) {
result[i] = function(num) {
return function() {
console.log("this is " + num);
}
}(i);
};
return result;
}
It is working OK but why the anonymous function here not wrapped in parenthesis like this (function(...))(i);
? And in which cases can parenthesis be omitted in anonymous function?
In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.
Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.
TL;DR Named functions are useful for a good debugging experience, while anonymous functions provides context scoping for easier development. Arrow functions should only be used when functions act as data.
Since the syntax for function declarations and function expressions is identical, JS tells which one you are using from the code around the function.
To stop it being a function declaration you need to use it in an expression. Wrapping it in parenthesis will will do that but preceding it with a =
will too (as will a host of other operators). Since there is a =
here, the parenthesis are unnecessary.
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