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.

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

Learn the fundamentals

Deepen your understanding with structured lessons on this topic.

View 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