Question:
Explain closures in JavaScript.
Quick answer:
It is a feature of JavaScript which allows you to access the context of the outer function from the inner function.
function getCounter() {
count = 0
return function {
count += 1
return count
}
}
Longer answer:
As we learned before, there are Higher Order Functions in JavaScript, which means you can create and return functions out of the functions.
As we also know, functions can access each of their outer scopes.
function a() {
let variable = "hello world"
function b() {
console.log(variable)
}
b()
}
a() // hello world
So what are closures? Closures extend previous examples in a bit. They preserve all context for a given function when we leave the parent function.
function a() {
let variable = "hello world"
function b() {
console.log(variable)
}
return b
}
a()() //hello world
We have left the a
function's scope during the run, but we still have reference to our variable
. That is closure.
Closures even allow us to modify the enclosing variable.
function generateCounter() {
count = 0
return function() {
count++
return count
}
}
counter1 = generateCounter()
counter2 = generateCounter()
counter1() // 1
counter1() // 2
counter1() // 3
// βοΈ This counter is different
counter2() // 1
Real-life applications:
Closures are the reason why currying works in most cases.
let sum2 = a => b => a + b // spot the closure π
Also, closures can help you to encapsulate some data from the public use.
function Counter() {
_count = 0
function inc() {
return ++_count
}
function dec() {
return --_count
}
function count() {
return _count
}
return { inc, dec, count }
}
let counter = Counter()
counter.inc() // 1
counter.inc() // 2
counter.dec() // 1
counter.count() // 1
counter._count = 1000
counter.count() // 1
// ^^^ Still 1, hack with _count haven't worked out
If you want to share more valuable cases, please add them as comments and I will add links to them to the post itself π€
Resources:
MDN/Closures
Other posts:
- JS interview in 2 minutes / Currying π₯
- JS interview in 2 minutes / Promise
- JS interview in 2 minutes / this π€―
Btw, I will post more fun stuff here and on Twitter. Let's be friends π
Top comments (1)
I assume currying and private variables werent there when JS was invented. But closure was an inherent feature. What was the original use case for closures?