Skip to main content

Scope

Scope is a mechanism that determines the availability of variables in your code.

Scope chain: scopes form a hierarchy so that child scopes can access variables from parent scopes, but not vice versa.

Note

A variable is visible to the code being executed if it is present in the current scope or in the scope chain.

Global scope

Variables declared at the very top level, that is, outside of any constructs like if, while, for and functions, are in the global scope, and they are available everywhere after they are declared.

const globalValue = 10;

console.log(globalValue); // 10

function foo() {
console.log(globalValue); // 10
}

for (let i = 0; i < 5; i++) {
console.log(globalValue); // 10

if (i === 2) {
console.log(globalValue); // 10
}
}

Block scope

Variables declared inside if and for statements, functions and other blocks of code enclosed in curly braces {} are in the block scope, and they are available only within this block of code or those nested inside it.

function foo() {
const a = 20;
console.log(a); // 20

for (let i = 0; i < 5; i++) {
console.log(a); // 20

if (i === 2) {
console.log(a); // 20
}
}
}

// ❌ Error! Variable a is not available in the global scope
console.log(a);

for (let i = 0; i < 3; i++) {
// ❌ Error! Variable a is not available in this scope
console.log(a);
}

Think of it as a house with rooms. The house is in the global scope. Each function and block create a new room nested inside the house. Variables declared inside these rooms are only available when you are in this room. Outside the room, these variables are not available.

for (let i = 0; i < 5; i++) {
const a = 20;
console.log(a); // 20

if (i === 2) {
const b = 30;
console.log(a); // 20
console.log(b); // 30
}

if (i === 3) {
console.log(a); // 20

// ❌ Error! Variable b is not available in this scope
console.log(b);
}
}

Scope chain look-up

The interpreter first tries to find a variable in the scope in which such variable was accessed. If there is no such variable in the local scope, then the interpreter goes out, one level per attempt, until it finds the necessary value or reaches the topmost scope (global) and realizes that no variable with such an identifier can be found, since it does not exist; then it will generate an error message that the variable is not declared.

Scope chain search