DEV Community

loading...
Cover image for JS interview in 2 minutes / Closure

JS interview in 2 minutes / Closure

kozlovzxc profile image Nikita Kozlov ・2 min read

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Real-life applications:
Closures are the reason why currying works in most cases.

let sum2 = a => b => a + b // spot the closure 🔎
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 👋

Discussion (1)

Collapse
z00md profile image
z00md

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?

Forem Open with the Forem app