Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 17, 2021 09:49 am GMT

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:

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To