Junior
What is a self-invoking function?
sobes.tech AI
Answer from AI
An Immediately Invoked Function Expression (IIFE) is a function that is defined and executed immediately after its creation.
It has the following structure:
- The function is declared inside parentheses
(). - Immediately after the declaration, another set of parentheses
()follows to invoke this function.
(function() {
// Code inside the function
})();
Main advantages of using IIFE:
- Scope isolation: All variables declared inside the IIFE are local to that function and do not pollute the global namespace.
- Creating private variables and functions: Thanks to scope isolation, private members can be created.
- Executing code immediately after definition: Useful for initialization or one-time code execution.
Example of IIFE with arguments:
(function(message) {
console.log(message); // Will output "Hello!"
})("Hello!");