0
0
Javascriptprogramming~5 mins

Scope chain in Javascript

Choose your learning style9 modes available
Introduction

The scope chain helps JavaScript find variables by looking in the right places step-by-step.

When you want to understand where a variable comes from in your code.
When you have functions inside other functions and want to access variables from outside.
When debugging why a variable has a certain value.
When writing code that uses nested functions or blocks.
When you want to avoid naming conflicts by knowing which variable is used.
Syntax
Javascript
function outer() {
  let outerVar = 'hello';
  function inner() {
    console.log(outerVar);
  }
  inner();
}

Variables are looked up starting from the current function, then moving outward.

If a variable is not found in the current scope, JavaScript checks the next outer scope.

Examples
The inner function sayHello uses the variable name from the outer function.
Javascript
function greet() {
  let name = 'Alice';
  function sayHello() {
    console.log('Hello ' + name);
  }
  sayHello();
}
greet();
The function check accesses a variable from the global scope.
Javascript
let globalVar = 'I am global';
function check() {
  console.log(globalVar);
}
check();
The inner function has its own x, so it prints 2, then the outer prints 1.
Javascript
function outer() {
  let x = 1;
  function inner() {
    let x = 2;
    console.log(x);
  }
  inner();
  console.log(x);
}
outer();
Sample Program

This program shows how the scope chain works with two variables named message in different scopes.

Javascript
function outer() {
  let message = 'Hi from outer';
  function inner() {
    let message = 'Hi from inner';
    console.log(message); // inner message
  }
  inner();
  console.log(message); // outer message
}
outer();
OutputSuccess
Important Notes

Each function creates a new scope for its variables.

If a variable is not found in the current scope, JavaScript looks outward until it finds it or reaches the global scope.

Variables declared with let and const are block-scoped, meaning they only exist inside the block they are declared in.

Summary

The scope chain is how JavaScript finds variables by checking current and outer scopes.

Inner functions can access variables from outer functions.

Variables with the same name in inner scopes hide outer ones.