C
h
i
L
L
u
.
.
.
Back to ArticlesUnderstanding JavaScript ClosuresJavaScript

Understanding JavaScript Closures

avatarSombir RedhuMar 8, 20263 min read142
javascriptclosuresfundamentals

A closure is a function that has access to its outer scope even after the outer function has returned. This is one of the most fundamental concepts in JavaScript.

Every time you create a function inside another function, you have created a closure. The inner function has access to the variables of the outer function.

function counter() {\n  let count = 0;\n  return function() {\n    count++;\n    return count;\n  };\n}\nconst increment = counter();\nconsole.log(increment()); // 1\nconsole.log(increment()); // 2

Closures are used everywhere in JavaScript — event handlers, callbacks, and module patterns all rely on closures.

Sponsored

Comments0

?

No comments yet. Be the first!