Sub topic 13
Function Declarations Inside Blocks
Earlier chapters covered function declarations at the top level of a script or function body. There, the rule is simple: the whole function is hoisted to the top of its scope. This chapter covers a less obvious case, a function declaration placed inside a block such as an if, a for loop, a switch, or a bare pair of braces { }.
The behavior depends on whether the code runs in strict mode. In strict mode the rule is clean and predictable. In sloppy (non-strict) mode, browsers follow a set of legacy compatibility rules that produce surprising results. You need to know both: you will read old code that relies on the sloppy rules, and you will write new code that should avoid them.
This chapter assumes you know:
- The hoisting and temporal dead zone rules from the earlier chapter.
- The difference between
var(function-scoped) andlet/const(block-scoped). - What
'use strict'does at a basic level.
A Short History
In ES5 the language specification did not allow function declarations inside blocks at all. Strict mode code that tried it got a SyntaxError. Every browser accepted them in sloppy mode anyway, and each engine gave them slightly different meanings. Code that worked in one browser could break in another.
ES2015 fixed this in two parts:
- In strict mode, function declarations in blocks became legal and block-scoped, much like
let. - For sloppy mode, the specification added "web legacy compatibility semantics" in Annex B. These rules describe the behavior that the old browsers mostly agreed on, so existing websites keep working.
Strict mode applies automatically inside ES modules (import/export files, <script type="module">) and inside class bodies. Classic scripts and Node.js CommonJS files are sloppy unless they start with 'use strict'.
Strict Mode: Block-Scoped and Hoisted Within the Block
In strict mode, a function declaration inside a block behaves as follows:
- It is visible only inside that block.
- It is hoisted to the top of the block with its body, so you can call it before its line within the block.
- It does not exist outside the block.
'use strict';
{
console.log(helper()); // inside (hoisted to the top of the block)
function helper() {
return 'inside';
}
}
console.log(typeof helper); // undefined (no binding exists out here)
try {
helper();
} catch (e) {
console.log(e instanceof ReferenceError); // true
}There is one difference from let: no temporal dead zone. A let binding cannot be touched until its declaration line runs. A block-level function declaration is created and initialized as soon as the block starts, so the call on the first line of the block works.
Strict mode also forbids declaring the same function name twice in one block:
'use strict';
// SyntaxError: Identifier 'twice' has already been declared
// {
// function twice() {}
// function twice() {}
// }Sloppy Mode: Two Bindings and a Copy
In sloppy mode, Annex B adds extra behavior on top of the block scoping. For a function declaration f inside a block, the engine does the following:
- It creates a block-scoped binding
finside the block, hoisted to the top of the block, exactly as in strict mode. - It also creates a
var-style bindingfin the enclosing function (or global) scope. That binding starts asundefined. - When execution reaches the function declaration's line inside the block, the engine copies the current value of the inner
finto the outerf.
The result is a function that exists outside the block, but only after the block has run. Save the following as a plain .js file with no 'use strict' and run it with node:
console.log(greet); // undefined (the var-style binding exists, but is empty)
try {
greet();
} catch (e) {
console.log(e instanceof TypeError); // true ("greet is not a function")
}
if (true) {
function greet() {
return 'hi';
}
}
console.log(greet()); // hi (copied out when the declaration line ran)Compare the errors. In strict mode, calling the function from outside the block gives a ReferenceError because the name does not exist. In sloppy mode, calling it before the block gives a TypeError because the name exists and holds undefined.
Edge Case: The Block Never Runs
If the block never executes, the copy never happens. The outer binding stays undefined:
// sloppy mode
if (false) {
function never() {
return 'unreachable';
}
}
console.log(never); // undefinedThis is how conditional function definitions in old code fail without an obvious error. The name exists, typeof never returns 'undefined', and the program fails later when something tries to call it.
Edge Case: Reassignment Inside the Block
The two bindings are separate, and the copy happens only once, at the declaration line. Assigning to the name inside the block afterwards changes only the inner binding:
// sloppy mode
{
function f() {
return 1;
}
f = function () {
return 2;
};
console.log(f()); // 2 (inner binding was reassigned)
}
console.log(f()); // 1 (outer binding got the value at the declaration line)Code like this is hard to read. The same name refers to two different functions depending on which side of a closing brace you are on.
Edge Case: Conflicts Switch Off the Legacy Behavior
Annex B applies only when adding an outer var would be legal. If an outer let, const, or class already uses the name, adding the var would be an error, so the engine skips that step. The function then stays block-scoped, even in sloppy mode:
// sloppy mode
let tool = 'outer';
{
function tool() {
return 'inner';
}
console.log(typeof tool); // function
}
console.log(tool); // outerEdge Case: `switch` Is One Block
All case clauses in a switch share a single block. A function declared in one case is hoisted to the top of the whole switch body and is visible in the other cases:
'use strict';
function run(mode) {
switch (mode) {
case 'a':
return shared();
case 'b':
function shared() {
return 'from case b';
}
return 'b';
}
}
console.log(run('a')); // from case bThis works, but readers do not expect it. If several cases need a helper, declare it before the switch.
Edge Case: Braceless `if`
Sloppy mode also accepts a declaration as the direct body of an if with no braces, such as if (x) function f() {}. Annex B treats it as if braces were present. In strict mode this is a SyntaxError. Inside loops (while (x) function f() {}) it is a SyntaxError in every mode.
Strict and Sloppy Compared
| Situation | Strict mode (and modules, classes) | Sloppy mode |
|---|---|---|
| Call before the declaration, inside the block | Works (hoisted to block top) | Works (hoisted to block top) |
| Access outside the block, before the block runs | `ReferenceError` | `undefined`; calling it throws `TypeError` |
| Access outside the block, after the block runs | `ReferenceError` | The function |
| Block never runs | Name never exists outside | Outer name stays `undefined` |
| Outer `let`/`const` with the same name | Block-only | Block-only (legacy step skipped) |
| Duplicate declarations in one block | `SyntaxError` | Allowed, last one wins |
| `if (x) function f() {}` without braces | `SyntaxError` | Allowed |
What to Write Instead
The usual reason to put a function declaration in a block is to choose an implementation based on a condition. Make that choice explicit with a function expression assigned to a variable in the scope where you need it:
'use strict';
const useFast = process.argv.includes('--fast');
const compute = useFast
? (n) => n * 2
: function slowCompute(n) {
let total = 0;
for (let i = 0; i < n; i++) total += 2;
return total;
};
console.log(compute(5)); // 10 either wayThis version gives the same result in every mode, compute is always defined, and a reader can see the choice in one place. If the branches are too long for a ternary, declare let compute; before the if and assign it in each branch.
Function declarations inside blocks are fine when the helper really belongs to that block and you are in strict mode. For example, a small helper used only inside one loop body can live there. What you should avoid is depending on a block-level declaration from outside its block.
Exercise
In a sloppy-mode script, what do the three console.log lines print? Code: console.log(typeof pick); if (Math.random() > 2) { function pick() { return 1; } } console.log(pick); console.log(typeof pick);
Show answer
All three print undefined (the first and third print the string "undefined"). Annex B creates an outer var binding named pick that starts as undefined. Math.random() never exceeds 2, so the block never runs, the copy never happens, and pick stays undefined.
Exercise
Add 'use strict' to the top of the previous script. What changes?
Show answer
The block-level pick is now visible only inside the block, so no outer binding exists. typeof pick still returns "undefined", because typeof does not throw on undeclared names. But console.log(pick) now throws a ReferenceError, and the third line never runs.
Exercise
A sloppy script has let format = null; at the top, and later if (ready) { function format(x) { return String(x); } }. After the if block runs with ready set to true, what is the value of format outside the block, and why?
Show answer
It is still null. Adding the legacy outer var named format would conflict with the existing let format, so Annex B skips that step. The function stays scoped to the block and never replaces the outer let binding.