Script Valley
JavaScript Tutorial for Beginners to Advanced
Control Flow and FunctionsLesson 3.4

Scope and Closures in JavaScript

global scope, function scope, block scope, lexical scope, closures, practical uses of closures

Scope and Closures in JavaScript

Scope determines where variables are accessible in your code. Closures are one of the most powerful and frequently misunderstood features in JavaScript. Once you understand them, you will see they appear everywhere — in callbacks, event handlers, and many popular design patterns.

Global and Function Scope

A variable declared outside any function is in the global scope and accessible everywhere. A variable declared inside a function is in function scope and only accessible within that function.

const globalMessage = 'I am global';

function showMessage() {
  const localMessage = 'I am local';
  console.log(globalMessage); // works
  console.log(localMessage);  // works
}

showMessage();
// console.log(localMessage); // ReferenceError

Block Scope

Variables declared with let and const are block-scoped — they only exist within the { } block where they were declared.

if (true) {
  let blockVar = 'inside if block';
  console.log(blockVar); // works
}
// console.log(blockVar); // ReferenceError

What Is a Closure?

A closure is created when an inner function retains access to the variables of its outer function, even after the outer function has finished executing. This happens because functions in JavaScript remember the scope they were created in.

function makeCounter() {
  let count = 0;

  return function() {
    count++;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

Here, the inner function retains access to count even after makeCounter has returned. Each call to counter() increments the same count variable.

Practical Uses of Closures

function createMultiplier(factor) {
  return (number) => number * factor;
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5));  // 10
console.log(triple(5));  // 15

Closures are used in module patterns, memoization, event handlers with preserved state, and many library implementations. They are one of the features that make JavaScript uniquely expressive.