The Function Statement in Blocks
You'll learn: How function declarations behave when placed inside if, else, or loop blocks — and why their behavior can be unpredictable.
The Core Idea
In JavaScript, you can technically write a function declaration inside a block (like an if statement or while loop), but the behavior is not standardized and varies between engines and modes.
if (true) {
function greet() {
return "Hello";
}
}
In strict mode, this function is block-scoped — it only exists inside the if block. In non-strict mode, older engines might hoist it to the entire function or global scope, making it accessible outside the block. This inconsistency makes block-level function declarations unreliable.
Why This Matters
When you learned about hoisting, you saw that function declarations are hoisted to the top of their scope. But which scope? If you put a function inside an if block, different JavaScript engines historically disagreed:
- Some hoisted it to the outer scope
- Others kept it block-scoped
- Behavior changed between strict and non-strict mode
Modern best practice: Use function expressions inside blocks instead:
let greet;
if (true) {
greet = function() {
return "Hello";
};
}
This is predictable, clear, and works consistently across all environments.
Key Takeaway: Avoid function declarations inside if, else, or loop blocks — their hoisting behavior is inconsistent. Use function expressions assigned to variables instead for reliable, block-scoped functions.