Skip to content

Scope

In one line

Scope is the region of your program where a variable is visible and can be used.

In simple words

Scope decides where a variable "lives" and where you are allowed to reference it. A variable declared inside a function is not visible outside that function — its scope is local. A variable declared at the top level of the file is global and visible everywhere.

Scope prevents naming collisions. You can have a variable called i inside one function and another i inside a different function, and they will not interfere with each other because each has its own local scope.

Most modern languages use lexical (static) scope — the scope is determined by where the variable is written in the source code, not by where the function is called. Block scope (introduced by let and const in JavaScript) confines a variable to the nearest curly-brace block.

Example

javascript
// Global scope — visible everywhere
var globalVar = "I am global";

function outer() {
  // Function scope — visible only inside outer()
  var functionVar = "I am function-scoped";

  if (true) {
    // Block scope — visible only inside this block
    let blockVar = "I am block-scoped";
    console.log(globalVar, functionVar, blockVar); // ✅ all accessible
  }

  console.log(blockVar); // ❌ ReferenceError: blockVar is not defined
}

outer();
console.log(functionVar); // ❌ ReferenceError: functionVar is not defined

Three scope levels in action: globalVar is accessible everywhere, functionVar only inside outer(), and blockVar only inside the if-block. Accessing them outside their scope throws a ReferenceError.

How it works

  1. Global scope — variables declared outside any function or block; visible everywhere.
  2. Function scope — variables declared inside a function; visible only within that function.
  3. Block scope — variables declared with let/const inside {}; visible only in that block.
  4. When code references a variable, the interpreter searches the current scope, then outer scopes, up to global.

Common confusions

  • Confused with: context

    The difference: Scope is about which variables are visible (a compile-time concept); context is about what this refers to at runtime. They are related but distinct.

Related terms

Related Resources

Related Lessons

  • Variables

    Scope is introduced alongside variables

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