An immediately invoked function expression (IIFE) is a JavaScript function that is executed immediately after it is defined. It is created by wrapping a function expression in parentheses and then adding a second pair of parentheses at the end. This tells the JavaScript engine to invoke the function as soon as it is evaluated.
IIFEs have a number of advantages over traditional JavaScript functions, including:
- They prevent global variable pollution. Variables defined inside an IIFE are only accessible within the function itself, not in the global scope. This can help to avoid naming conflicts and other errors.
- They can be used to create self-contained modules. IIFEs can be used to encapsulate code and data into reusable modules. This can make your code more modular and easier to maintain.
- They can be used to initialize data and execute code as soon as the page loads. This can be useful for things like setting up event listeners or initializing global state.
Here's the basic syntax of an IIFE:
(function() { // code here })();
Basic IIFE
In this example, the function is defined and immediately executed. It will log 'This is an IIFE' to the console.
(function() { console.log('This is an IIFE'); })();
IIFE with Parameters
In this case, we're passing a parameter name to the IIFE, and it logs 'Hello, John' to the console.
(function(name) { console.log('Hello, ' + name); })('John');
To create anonymous functions:
This IIFE creates an anonymous function that can be assigned to a variable and then called later.
let myFunction = (function() { // Code for my function })(); myFunction();
This IIFE creates a private variable name and then returns a function that logs the message "Hello, name!" to the console:
(function() { let name = "John"; return function() { console.log("Hello, " + name + "!"); }; })(); // Call the function returned by the IIFE: var greeting = (function() { let name = "John"; return function() { console.log("Hello, " + name + "!"); }; })(); greeting(); // Logs "Hello, John!" to the console.