I am studying JavaScript and I sometimes see something like this
function functionname()
{
// Some statements
} () ;
What does () following } mean?
Thanks a lot, experts on Stack Overflow
I am studying JavaScript and I sometimes see something like this
function functionname()
{
// Some statements
} () ;
What does () following } mean?
Thanks a lot, experts on Stack Overflow
That is an IIFE (immediately invoked function expression). It is used to create a new scope. For example:
var x = 10;
(function() {
var x = 5;
}());
alert(x); // still 10
All it does is define and call the function at the same time.
IIFEs are also used to "save" the value of a variable. For example, this code won't work:
for (var i = 0; i < buttons.length; i ++) {
buttons[i].onclick = function() { alert(i) }
}
Every button will alert the last index when you click it, because after the loop is done i
is buttons.length
. To fix it, you would use an IIFE:
for (var i = 0; i < buttons.length; i ++) {
buttons[i].onclick = (function(i) {
return function() {
alert(i)
}
})(i)
}
It calls the function.
var foo = function () { return 1; }();
alert(foo); // 1
There are lots of ways to define a function, when you do it like this ...
(function functionname(innerArguments){
// Some statements;
})(outerArguments);
... the function is executed as soon as this piece of code is interpreted; its the same as:
function functionname(innerArguments){
// Some statements;
};
functionname(outerArguments);