#73: A variable declared inside an IIFE
Topic: scope · Difficulty: ★
(function () {
var secret = 'hidden';
})();
console.log(typeof secret);Output
undefined
Why
An Immediately Invoked Function Expression (IIFE) runs a function the instant it's defined, and its main historical purpose is exactly this: creating a private scope. secret is declared with var inside the function body, so it is scoped to that function call and destroyed once the function returns — it never becomes a variable of the outer (here, top-level) scope. Asking for typeof secret outside finds no such variable in scope, and typeof is specifically safe to use on names that were never declared at all: it returns 'undefined' instead of throwing.