2 min read

Scope and Scope Chain

Scope determines the accessibility (visibility) of variables. JavaScript has 3 types of scope: Block scope, Function scope, and Global scope.

1. Types of Scope

Global Scope

Variables declared outside any function have Global Scope. They can be accessed from anywhere in the script.

var globalVar = "I am global";

function check() {
  console.log(globalVar); // Accessible
}

Function Scope

Variables declared within a function are local to that function.

function myFunc() {
  var local = "I am local";
}
console.log(local); // ReferenceError

Block Scope (ES6)

let and const provide Block Scope (variables exist only within the {} block). var does not have block scope.

if (true) {
  let blockScoped = "Visible only inside if";
  var functionScoped = "Visible outside if";
}
console.log(blockScoped); // ReferenceError
console.log(functionScoped); // "Visible outside if"

2. The Scope Chain

When code attempts to access a variable, the JavaScript engine looks for it in the current scope. If it doesn't find it, it looks in the outer scope (parent). It continues up the chain until it reaches the Global Scope. This hierarchy is called the Scope Chain.

const global = "Global";

function outer() {
  const outerVar = "Outer";

  function inner() {
    const innerVar = "Inner";

    console.log(innerVar); // Found in current scope
    console.log(outerVar); // Found in parent scope
    console.log(global);   // Found in global scope
  }

  inner();
}

3. Lexical Scoping

JavaScript uses Lexical Scoping (static scoping). This means the scope is determined by the position of the function in the source code, not where it is called.

programming/javascript/vanilla/javascript programming/javascript/vanilla/closures programming/javascript/vanilla/hoisting