Menu

JavaScript Closures Explained with Simple Examples
📰

JavaScript Closures Explained with Simple Examples

DEV Community: beginners·Lavkush Kumar·6 days ago
#SAqOqTYm
#devtobeginners#devto#dev#function#closure
Reading 0:00
15s threshold

Originally published on CodingCush .

A closure is a function that remembers the variables from the place where it was created, even after that place has finished running. That sentence explains a lot of JavaScript behaviour that feels like magic at first: counters that keep counting, buttons that remember their own value, and helpers that carry private data. In this guide you will learn what a closure really is, how lexical scope makes it work, and how to use closures in real code, with every example tested in Node.js.

What Is a Closure, in Plain Words?

Imagine a backpack. When a function is created inside another function, JavaScript quietly packs the variables around it into a backpack and hands that backpack to the inner function. Wherever the inner function goes later, the backpack goes with it. The inner function can open the backpack and use those variables at any time.

The formal definition is not much scarier.…

Continue reading — create a free account

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