Why are parenthesis used to wrap a JavaScript function call?

In JavaScript, functions wrapped with parentheses 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 decreases clashing with other libraries. This is what we call Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function.

Syntax

(function() {
   // code
})();

As you can see above, the first pair of parentheses converts the code inside into an expression:

(function(){...})

The second pair of parentheses immediately calls the function that resulted from the expression above.

Example: Basic IIFE

(function() {
    console.log("This function runs immediately!");
})();

console.log("Code after IIFE");
This function runs immediately!
Code after IIFE

Why Use IIFE?

IIFE creates a private scope, preventing variables from polluting the global namespace:

// Without IIFE - global pollution
var counter = 0;

// With IIFE - private scope
(function() {
    var counter = 0;
    console.log("Private counter:", counter);
})();

console.log("Global scope remains clean");
Private counter: 0
Global scope remains clean

IIFE with Parameters

(function(name, version) {
    console.log(`App: ${name} v${version}`);
})("MyApp", "1.0.0");
App: MyApp v1.0.0

Alternative Syntax

You can also place the parentheses around the entire expression:

// Style 1 (more common)
(function() {
    console.log("Style 1");
})();

// Style 2 (alternative)
(function() {
    console.log("Style 2");
}());
Style 1
Style 2

Conclusion

Parentheses around JavaScript functions create IIFEs, which execute immediately and provide private scope. This pattern prevents global namespace pollution and is essential for modular code organization.

Updated on: 2026-03-15T22:17:44+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements