Menu

1 / 4

JavaScript Closures Explained — Build Private Variables, Function Factories, and Stateful Functions

JavaScript in Plain English - Medium·Zayd Islam·4 days ago
#XDNGi9HK
Reading 0:00
15s threshold

Member-only story

JavaScript Closures Explained — Build Private Variables, Function Factories, and Stateful Functions

JavaScript Mastery Series Part 35

Zayd Islam

8 min read14 hours ago

Read Part 34

Press enter or click to view image in full size

Discover how JavaScript functions remember variables from their surrounding scope, even after the outer function has finished executing.

Have you ever wondered how a function can access a variable that should no longer exist?

Consider this example:

function createCounter() {

let count = 0;

return function () {

count++;

return count;

};

}

const counter = createCounter();

console.log(counter()); // 1

console.log(counter()); // 2

console.log(counter()); // 3

Something interesting is happening here.

The createCounter() function has already finished executing, yet the returned function can still access and update count .

How?

The answer is closures.

Closures are one of JavaScript’s most powerful features.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.