Course contentsShow
← JavaScript
Lesson 425 of 2,72311. FunctionsFree lesson

Hoisting in Block Scope

Explore how function declarations inside blocks behave differently depending on strict mode.

Hoisting in Block Scope

You'll learn how function declarations behave differently inside blocks depending on whether strict mode is enabled.

The Core Behavior

When you declare a function inside a block (like an if statement or a plain {}), its hoisting behavior changes based on strict mode. In non-strict mode, function declarations inside blocks get hoisted to the top of the enclosing function (or global scope), creating confusing and unpredictable behavior. In strict mode, function declarations are block-scoped—they're only accessible within that specific block, just like let and const.

Think of it like mail delivery: in non-strict mode, a letter addressed to "Apartment 3B" might accidentally be delivered to the entire building's lobby. In strict mode, it goes exactly where it should—only to Apartment 3B.

Why This Matters

// Non-strict mode (confusing!)
function example() {
    if (true) {
        function greet() {
            return "Hello";
        }
    }
    greet(); // Works! Function escaped the block
}

// Strict mode (predictable)
"use strict";
function example2() {
    if (true) {
        function greet() {
            return "Hello";
        }
    }
    greet(); // ReferenceError: greet is not defined
}

In strict mode, greet stays inside the if block where it was declared. Outside that block, it doesn't exist.

Key Takeaway: Always use strict mode ("use strict";) to make function declarations inside blocks behave predictably—they'll be block-scoped and won't leak out to the surrounding function.