JavaScript Intermediate

What are Scope and Scope Chain in JavaScript?

AI Practice

Scope

Scope defines where variables can be accessed. JavaScript has three types:

1. Global Scope

var globalVar = 'I am global';
function foo() {
  console.log(globalVar); // accessible
}

2. Function Scope

function foo() {
  var localVar = 'I am local';
  console.log(localVar); // ✅
}
console.log(localVar); // ❌ ReferenceError

3. Block Scope

ES6 let and const have block scope:

{
  let x = 10;
  const y = 20;
}
console.log(x); // ❌ ReferenceError

Scope Chain

When a variable is not found in the current scope, JavaScript walks up the outer scopes until it reaches the global scope. This lookup path is called the scope chain.

const global = 'global';

function outer() {
  const outerVar = 'outer';

  function inner() {
    const innerVar = 'inner';
    console.log(innerVar);  // 'inner' (found locally)
    console.log(outerVar);  // 'outer' (found in outer)
    console.log(global);    // 'global' (found globally)
  }

  inner();
}

outer();

Lookup order: innerouter → global → ReferenceError if not found.


Lexical Scope

JavaScript uses lexical (static) scoping — the scope chain is determined at write time, not at call time.

✦ AI Mock Interview

Type your answer and get instant AI feedback

Sign in to use AI scoring

Copyright © 2026 Wood All Rights Reserved · FE Interview Hub