javascript
javascript
Closures in Javascript
Live
bolt
Level1
Progress0%

Closures in Javascript

CARD 1

Introduction

Login to report note issues for this section.

Closures

A closure is a function that remembers and has access to variables from its outer (enclosing) scope even after that outer function has finished executing.

In other words — a closure is a function bundled together with its surrounding state (the lexical environment where it was defined).

codejs
1function outer() {
2  let count = 0; // outer variable
3
4  function inner() {
5    count++;
6    console.log(count);
7  }
8
9  return inner;
10}
11
12const counter = outer(); // outer() finishes executing here
13counter(); // 1 — inner still has access to count
14counter(); // 2
15counter(); // 3

outer() has returned and is finished. Normally, count would be destroyed. But inner holds a reference to count through a closure — so count persists in memory as long as inner is alive.