![]() |
VOOZH | about |
Immediately Invoked Function Expressions (IIFE) are JavaScript functions that are executed immediately after they are defined. They are typically used to create a local scope for variables to prevent them from polluting the global scope.
Syntax:
(function (){
// Function Logic Here.
})();
Example: Here's a basic example of an IIFE .
This is a local variable
Explanation: The function is wrapped in parentheses (function() { ... }), followed by () to immediately invoke it.
Example 2: Here's another example of an IIFE that stores and display result.
30
Explanation: The IIFE is immediately invoked and returns the sum of x and y. The result of the IIFE, which is 30, is assigned to the variable result.
IIFEs are commonly used to create private scope in JavaScript, allowing variables and functions to be encapsulated and inaccessible from outside the function.
Example: Here's an example demonstrating how an IIFE can be used to create private variables:
3 undefined
Explanation: Here, count is a private variable scoped to the IIFE, inaccessible from outside. The returned object exposes methods (increment, decrement, and getCount) that allow controlled manipulation and access to the private count variable.