Skip to content

OutputNot attempted

var hoisting inside a nested IIFE

var x = 23;
(function () {
var x = 43;
(function random() {
console.log(x);
var x = 21;
})();
})();

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

The innermost function has its own var x, hoisted to the top of that function (initialised to undefined). It shadows both outer x values, so the log sees undefined, not 43 or 23.