IIFE: Immediately Invoked Function Expression
An IIFE, or Immediately Invoked function Expression, is a common JavaScript design pattern used to create a self-contained and private scope for variables and functions.
Main benefits of using an IIFE is to avoid naming conflict and keep variables and functions private within a specific scope.
It consists of an anonymous functions expression that is defined and executed immediately after its creation.
Syntax
(function() {
//Your code here
})();
Here’s a real-life example of how an IIFE can be used:
(function() {
var name = "John";
function sayHello() {
console.log("Hello, " + name + "!");
}
sayHello();
})();
In this example, we’ve defined an IIFE that contains a variable name and a function sayHello. These variables and functions are encapsulated within the IIFE’s scope and do not pollute the global scope. When the IIFE is immediately invoked, it calls the sayHello function and prints “Hello, John!” to the console.
IIFE can be especially useful in scenarios where you’re working with multiple JavaScript files or libraries, ensuring that your code doesn’t unintentionally interfere with other code.
Note:
Some time you can get semicolon ; begging of iife function why that so. Let’s find out.
The semicolon at the beginning is used to ensure that the code executes correctly. This practice is particularly useful when concatenating or including multiple JavaScript files.
Example:
const a = 1
(function() {
// Your code here
})();
If const a = 1 is not followed by a semicolon, JavaScript might misinterpret the start of the IIFE, leading to unexpected errors.
When combining multiple JavaScript files, the semicolon ensures that each file is treated as a separate statement. This helps prevent issues where one file might accidentally affect the syntax of the next.
//example if iife with semicolon
// Code from another script (ensure it ends with a semicolon)
const globalValue = 42;
// Immediately Invoked Function Expression (IIFE)
;(function() {
// Local variable only accessible within this IIFE
const localValue = 'I am local';
// Access the global variable
console.log('Global value:', globalValue);
// Use the local variable
console.log('Local value:', localValue);
// Additional logic can go here
})();