IIFE Flashcards
What does IIFE stand for?
IIFE stands for Immediately Invoked Function Expression.
What is an IIFE?
An IIFE is a JavaScript function that runs as soon as it is defined.
How can you recognize an IIFE?
An IIFE is normally wrapped in a parenthesis which makes it a function expression followed by () which tells the JavaScript compiler to invoke or call immediately.
(function() {
statements
})();
How else is an IIFE known?
It is a design pattern which is also known as a Self-Executing Anonymous Function.
What are the two major parts of an IIFE?
The first part is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
The second part creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.
What happens if you assign the IFFE to a variable?
Assigning the IFFE to a variable stores the function’s return value, not the function definition itself.
Give an example of an IFFE…
(function() {
const a = “aaaa”;
console.log(a);
})();
console.log(a); // Uncaught ReferenceError: a is not defined
In simple terms, why do we use IIFE?
Mainly because of privacy. Any variables declared inside the IIFE are not accessible from outside of the IIFE.