JavaScript Interview Question #6

What is scope in JavaScript?

JavaScript Fundamentals, Types, Scope & Functions Junior Beginner

Quick Interview Answer

Scope determines where a variable or function can be accessed. JavaScript commonly has global scope, function scope, block scope, and module scope.

Detailed Explanation

Scope determines where a variable or function can be accessed. JavaScript commonly has global scope, function scope, block scope, and module scope.

Variables declared with let and const respect block scope, while var is scoped to the containing function rather than an if, for, or other ordinary block. Understanding scope is important for preventing accidental variable access, naming conflicts, and state-related bugs.

Code Example

const globalValue = "global";

function demo() {
    const functionValue = "function";

    if (true) {
        const blockValue = "block";
        console.log(globalValue, functionValue, blockValue);
    }

    // console.log(blockValue); // ReferenceError
}