An Interest In:
Web News this Week
- February 28, 2024
- February 27, 2024
- February 26, 2024
- February 25, 2024
- February 24, 2024
- February 23, 2024
- February 22, 2024
JS interview in 2 minutes / Closure
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() // 1counter1() // 2counter1() // 3// This counter is differentcounter2() // 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() // 1counter.inc() // 2counter.dec() // 1counter.count() // 1counter._count = 1000counter.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
Original Link: https://dev.to/kozlovzxc/js-interview-in-2-minutes-closure-3hi6
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To