whatstheoutput_

#67: A function declared inside an if block

Topic: hoisting · Difficulty: ★★

if (true) {
  function greet() { return 'inner'; }
}
console.log(typeof greet);
console.log(greet());

Output

function
inner

Why

Function declarations inside a block are, per spec, block-scoped — greet should not exist outside the if block at all. But for legacy web compatibility, non-strict (sloppy) mode adds 'Annex B' semantics: a var-like binding for the function's name is also hoisted to the enclosing function/global scope, and gets synced to the block's function value once the block executes. node -e runs in sloppy mode, so typeof greet is 'function' outside the block and calling it returns 'inner'. In strict mode or ES modules, this leak does not happen and greet would be undefined outside the block.

More hoisting puzzles

Play today's puzzle →