DEV Community

Samrat
Samrat

Posted on

Closure in JavaScript

Closure is nothing but a technique bringing out the variable to the outer scope so that parent scope can also work with the variable from child scope.

function foo(){
    let count = 0;
    return function(){
        return count+=1;
    }}

let doo = foo();

console.log(doo());
console.log(doo());
console.log(doo());
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Here count variable can be mutated from the outer scope.
But count variable cannot be accessed directly from outside the foo function.

Top comments (2)

Collapse
 
parzival_computer profile image
Parzival

Interesting.

Collapse
 
sethcalebweeks profile image
Caleb Weeks

I think it would be more accurate to say that closures "close over" or encapsulate the scope of a variable. They don't bring the value into the outer scope, but instead provide a mechanism to access the encapsulated value. Also, it would help to provide the result of the console logs to get an idea of what it's actually doing.