Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript () following } [duplicate]

Tags:

javascript

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

like image 328
Doraemon Nobita Avatar asked Feb 27 '26 21:02

Doraemon Nobita


1 Answers

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)
}

More info on IIFEs

like image 163
tckmn Avatar answered Mar 01 '26 09:03

tckmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!