DEV Community

zain ul abdin
zain ul abdin

Posted on

What Are JavaScript Closures?

Let's talk about a JavaScript feature that is simple to understand but powerful when mastered: Closures.

They are functions that have access to their own scope, the outer function’s scope, and the global scope. They allow a function to remember the environment where it was created, even after that function is executed.

Consider this example:

function createCounter() {
 let count = 0; // This `count` is enclosed in the closure

 return function() { // The returned function forms a closure
 count++;
 console.log(count);
 };
}

const counter = createCounter();
counter(); // Output: 1
counter(); // Output: 2
Enter fullscreen mode Exit fullscreen mode

Here, createCounter creates a closure that "remembers" the count variable even after it’s done executing. Every time you call counter(), it still has access to count!

Closures allow us to create private variables, implement function factories, and write more modular and maintainable code.


To stay updated with more content related to web development and AI, feel free to follow me. Let's learn and grow together!

Top comments (0)