Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What are immediate functions in JavaScript?
Immediate functions in JavaScript are functions that execute automatically as soon as they are defined. They are also known as Immediately Invoked Function Expressions (IIFEs). These functions help create private scope and avoid polluting the global namespace.
Syntax
(function() {
// Code here executes immediately
})();
// Alternative syntax
(function() {
// Code here executes immediately
}());
Basic Example
<script>
(function() {
var message = "Hello from IIFE!";
console.log(message);
})();
// This variable is not accessible outside
// console.log(message); // Would cause an error
</script>
Hello from IIFE!
Comparison: Regular Function vs IIFE
Here's how a regular function differs from an immediate function:
<script>
// Regular function - needs to be called
function regularFunction() {
var str = "I need to be called";
console.log(str);
}
regularFunction(); // Must call explicitly
// IIFE - executes immediately
(function() {
var str = "I execute automatically";
console.log(str);
})();
</script>
I need to be called I execute automatically
IIFE with Parameters
<script>
var name = 'Amit';
(function(studentName) {
console.log('Student name = ' + studentName);
})(name);
</script>
Student name = Amit
Key Benefits
| Feature | Regular Function | IIFE |
|---|---|---|
| Execution | Manual call required | Automatic execution |
| Global namespace | Can pollute global scope | Creates private scope |
| Variable access | Variables may be global | Variables are private |
Common Use Cases
<script>
// Creating a module pattern
var myModule = (function() {
var privateVar = "I'm private";
return {
publicMethod: function() {
console.log("Accessing: " + privateVar);
}
};
})();
myModule.publicMethod();
</script>
Accessing: I'm private
Conclusion
Immediate functions (IIFEs) execute automatically and create private scope, preventing global namespace pollution. They're essential for module patterns and avoiding variable conflicts in JavaScript applications.
Advertisements
