DEV Community

zain ul abdin
zain ul abdin

Posted on

2

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!

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay