JavaScript - IIFE & Hoisting
Overview
Estimated time: 20–30 minutes
IIFEs create a scope immediately. Before modules and block scope, they were common to avoid globals.
Learning Objectives
- Write IIFEs and understand their scoping.
- Recap hoisting differences (declarations vs expressions).
- Prefer modern alternatives (modules, blocks).
Prerequisites
Examples
// IIFE classic
(function(){
const secret = 42;
console.log('init');
})();
// Arrow IIFE
(() => {
const temp = 'ok';
})();
// Block as modern alternative
{
const scoped = 1; // not visible outside
}
Hoisting recap
- Function declarations hoist with their body.
let
/const
are hoisted but in TDZ until initialized.
Common Pitfalls
- Unnecessary IIFEs when modules or blocks suffice.