Problem Statement
What is the purpose of an IIFE in JavaScript? Give a practical use case.
Explanation
An IIFE, or Immediately Invoked Function Expression, runs as soon as it is defined.
It creates a private area where variables cannot be accessed from outside.
Developers used IIFEs before ES6 modules to protect code and avoid global variable pollution.
They are still useful for one-time setups, like initializing configurations or starting timers.
Think of IIFE as a self-executing container that keeps your code safe and clean.
Code Solution
SolutionRead Only
(function() {
const secret = 'hidden';
console.log('IIFE executed');
})();
// secret is not accessible outside
// console.log(secret); // Error