Scope

What is Scope in JavaScript?

Scope is an important concept to understand when using JavaScript. It controls where variables can be accessed or referenced in your code and plays a big role in keeping your programs clean, modular, and bug-free.

When a variable is "in scope," you are allowed to reference it and work with it. When a variable is "out of scope," trying to access it will cause an error, usually a ReferenceError. This is JavaScript's way of saying, "I don't know what you're talking about — that variable doesn't exist here."

{
    let blockVariable = "I'm inside a block!";
    console.log(blockVariable);  // Works fine
}

console.log(blockVariable);    // ReferenceError

Blocks and Scope

A block in JavaScript is any code that is wrapped in curly brackets such as:

if (condition) { 
    // block
}

for (let i = 0; i < 5; i++) { 
    // block
}

function myFunction() { 
    // block
}

If a variable is declared inside that block, it is “in-scope”. Declaring a variable outside of any blocks is known as a global variable and are said to have global scope and can be accessed anywhere in your JavaScript code. Too many global variables may cause issues in your code due to scope pollution, so if you can, make some of your variables block scoped.

let globalVariable = "I'm global!";

function sayHello() {
    console.log(globalVariable);  // Accessible here
}

sayHello();
console.log(globalVariable);    // Accessible here too