Sub topic 13
Function Declarations Inside Blocks
This chapter assumes you know how hoisting works for top-level function declarations and how let and const are scoped to blocks. A block is any code between { and } that is not a function body. Examples are the bodies of if, for, and while, or a bare { }.
Declaring a function inside a block is legal. Its behavior depends on whether the code runs in strict mode, so it is one of the less predictable corners of the language.
Strict Mode: Block-Scoped Functions
In strict mode, a function declaration inside a block behaves much like a let binding. Strict mode covers ES modules, class bodies, and files that start with 'use strict'. The function is hoisted to the top of its block, so you can call it earlier in that block. It does not exist outside the block.
'use strict';
if (true) {
console.log(greet()); // hi (hoisted within the block)
function greet() {
return 'hi';
}
}
console.log(typeof greet); // "undefined" (not visible outside)This is the clean, standard behavior. The function belongs to the block it is written in.
Sloppy Mode: The Legacy Rules
Non-strict ("sloppy") code follows compatibility rules from Annex B of the specification. Plain browser scripts and CommonJS files without 'use strict' run in sloppy mode. Old browsers handled block-level functions in different ways, and Annex B keeps existing websites working by giving the function two bindings:
- A block-scoped binding, hoisted within the block as in strict mode.
- A
var-style binding in the enclosing function or script. It starts asundefinedand gets the function only when execution reaches the declaration.
// Run as a non-module script without 'use strict'
console.log(typeof greet); // "undefined" (var-like binding exists, empty)
if (true) {
function greet() {
return 'hi';
}
}
console.log(typeof greet); // "function" (copied out when the block ran)If the block never runs, the outer binding stays undefined:
// Non-strict script
if (false) {
function setup() {
return 'ready';
}
}
try {
setup();
} catch (e) {
console.log(e instanceof TypeError); // true: setup is not a function
}The error is a TypeError, not a ReferenceError. The name exists, but its value is undefined. Sloppy mode turns an unexpected result into a confusing one.
Comparing the Two Modes
| Question | Strict mode | Sloppy mode |
|---|---|---|
| Callable earlier in the same block? | Yes | Yes |
| Visible after the block? | No | Yes, if the block ran |
| Value outside before the block runs | Not defined | `undefined` |
| Calling it when the block never ran | `ReferenceError` | `TypeError` |
The Recommended Pattern
If a function's definition depends on a condition, assign a function expression to a variable you declare outside the block. The scope and the timing are then explicit.
const useUpper = true;
const format = useUpper
? (s) => s.toUpperCase()
: (s) => s;
console.log(format('hello')); // HELLOWhen the branches are too long for a ternary, declare let format; before the if and assign it in each branch. A function that exists only to help code inside one block can stay a declaration there, as long as the file is strict. The safest default is to put function declarations at the top level of a module or function body.
Exercise
In a non-strict script, if (Math.random() > 2) { function run() {} } is followed by run();. What happens, and what would happen in an ES module?
Show answer
The condition is always false, so the block never runs. In the sloppy script, run is a var-like binding that is still undefined, so run() throws a TypeError ("run is not a function"). In an ES module (strict mode), run exists only inside the block, so run() outside it throws a ReferenceError.
Exercise
Rewrite this sloppy-mode code so it works the same in strict and non-strict mode: if (debug) { function log(m) { console.log(m); } } else { function log() {} }
Show answer
Declare the variable outside the block and assign a function expression: const log = debug ? (m) => console.log(m) : () => {};. Now log is always defined after this line and is scoped the same way in both modes.