Skip to content

Scope

In one line

Scope is the region of code where a variable is accessible — it determines what variables you can see from a given point.

In simple words

Scope is the set of rules that determines where variables are visible. JavaScript has three main types: global scope (visible everywhere), function scope (visible within a function), and block scope (visible within a { } block).

var is function-scoped — it is visible throughout the enclosing function, even outside the block where it was declared. let and const are block-scoped — they are only visible within the nearest { } block.

Understanding scope is crucial for avoiding naming conflicts, managing variable lifetimes, and writing predictable code. Closures rely on scope: an inner function can access variables from its outer scope even after the outer function returns.

Example

javascript
function demo() {
  let blockScoped = "inside block";
  if (true) {
    let inner = "only here";
    console.log(blockScoped); // OK
  }
  // console.log(inner); // ReferenceError
}

blockScoped is visible throughout the function. inner is only visible inside the if block.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary