Skip to main content
D
JavaScript
JavaScript Closures

JavaScript Closures

JavaScript closures allow functions to remember their outer variables.

Read Time
5 min read
Difficulty
Beginner
Last Updated
Jun 15, 2026
Version
v1.0.0

Introduction

JavaScript closures happen when a function inside another function remembers the variables from its parent. Even after the parent function finishes running, the inner function still has access to those original variables. Developers use this to create private data.

Example

Example
1/* this creates a closure */
2function makeCounter() {
3  let count = 0;
4  return function() {
5    count++;
6    return count;
7  }
8}
9let counter = makeCounter();

Key Points

  • Closures remember variables from parent functions.
  • They allow for data privacy and encapsulation.
  • They are created automatically when functions are nested.
  • Memory leaks can occur if closures are misused.

Up Next

Continue your journey with the next topic.

Go to JS Callbacks