$4.45

What is the (function() { } )() construct in JavaScript?

Ask a question+
2

I used to know what this meant, but I’m struggling now…

(function () {

})();

add comment

2 Answers

3

This is the format of Self-Invoking Anonymous function

A self-invoking anonymous function runs automatically/immediately when you create it and has no name, hence called anonymous.

The self invoked function is made up of two parts the anonymous part:

(function() {

// some code here

})

Then the call to execute which is simply the closing braces

()

There’s another format through which you can do the same thing. Instead of putting the brackets, you can actually use the exclamation point like such

!function() {
// some code here
}()

Why use an anonymous function?
The advantage of using an anonymous function rather than writing the code directly is that the variables and functions defined within the anonymous function are not available to the code outside it. This prevents the global namespace from becoming littered with variables and functions that may not be needed further.

For example:

(function(){ 
    var x = 123; 
    alert(x); 
})(); 

alert(x);

This will first alert “123” and then throw an error on the next alert because x is not defined.

darbinyanraf 130
add comment
0

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.

It has nothing to do with any event-handler for any events (such as document.onload).
The first pair of parentheses (function(){…}) turns the code within (in this case, a function) into an expression, and the second pair of parentheses (function(){…})() calls the function that results from that evaluated expression.

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:

(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// …
})();
// foo is unreachable here (it’s undefined)

add comment

Your Answer