Skip to content

JavaScript Tutorial Functions

JavaScript Scope and Lexical Scope

Lesson 59 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Scope is the part of the code where a variable is visible. Code can only use a variable that is in scope.

Global scope

A variable declared outside any function or block is global: every part of the script can use it.

script.js
JS
const appName = "Notes";   // global

function show() {
  console.log(appName);    // → Notes
}
show();

Too many globals make large programs fragile, because any code can change them. Keep variables as local as possible.

Function scope

A variable declared inside a function exists only inside it.

script.js
JS
function calculate() {
  const secret = 42;
  return secret * 2;
}

console.log(calculate()); // → 84
console.log(typeof secret); // → undefined

Block scope

let and const are limited to the nearest { } block (an if, a loop, or a plain block). var ignores blocks, as shown in var and Hoisting.

script.js
JS
for (let i = 0; i < 2; i++) {
  const message = "round " + i;
  console.log(message);
}
console.log(typeof i, typeof message); // → undefined undefined

Lexical scope

JavaScript uses lexical scope: where a function is written decides which variables it can see, not where it is called from. An inner function can read variables of the outer ones around it.

script.js
JS
const greeting = "Hello";

function outer() {
  const name = "Maya";

  function inner() {
    console.log(`${greeting}, ${name}`); // sees both
  }

  inner();
}

outer(); // → Hello, Maya

The scope chain

When JavaScript looks for a variable, it starts in the current scope, then goes outward one level at a time until it finds it or reaches the global scope.

script.js
JS
const x = "global";

function a() {
  const x = "a's own";
  function b() {
    console.log(x); // → a's own   (the nearest x wins)
  }
  b();
}
a();

An inner variable with the same name shadows the outer one. It is legal but can confuse readers, so avoid reusing names.

Why it matters

Scope explains many “variable is not defined” errors, and it is the foundation of closures, the next lesson.

lightbulb
Keep scopes small
Declare variables as close as possible to where you use them, and prefer const. Smaller scopes mean fewer places for bugs to hide.