Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})();
but
In javascript, this is called Immediately-Invoked Function Expression (IIFE) .
In order to make it a function expression you've to:
enclose it using ()
place a void operator before it
assign it to a variable.
Otherwise it will be treated as function definition and then you won't be able to call/invoke it at the same time by the following way:
function (arg1) { console.log(arg1) }();
The above will give you error. Because you can only invoke a function expression immediately.
This can be achieved couple of ways: Way 1:
(function(arg1, arg2){
//some code
})(var1, var2);
Way 2:
(function(arg1, arg2){
//some code
}(var1, var2));
Way 3:
void function(arg1, arg2){
//some code
}(var1, var2);
way 4:
var ll = function (arg1, arg2) {
console.log(arg1, arg2);
}(var1, var2);
All above will immediately invoke the function expression.