Scope

Intermediate·20 min read·Lesson 2 of 8·Not Started

Scope determines the accessibility of variables in JavaScript. Understanding scope is crucial for writing predictable code.

Types of Scope

  • Global scope: variables declared outside any function or block
  • Function scope: variables declared with var inside a function
  • Block scope: variables declared with let and const inside a block {}

Lexical Scoping

JavaScript uses lexical scoping, meaning a function's scope is determined by its position in the source code. Inner functions have access to variables in their outer (parent) scopes.

The Scope Chain

When a variable is referenced, JavaScript traverses the scope chain — from local scope outward to global scope — until it finds the variable or throws a ReferenceError.