Closures in JavaScript: Video

A JavaScript closure is a function which remembers the environment in which it was created. We can think of it as an object with one method and private variables. JavaScript closures are a special kind of object which contains the function and the local scope of the function with all the variables (environment) when the closure was created.

// normal closure
 
function Add(num1) {
 
    function Addfoo(num2) {
        let result = num1 + num2;
        return result;
    }
 
    return Addfoo;
}
 
 
var a1 = Add(9)(2);
console.log(a1);
var b1 = Add(15)(12);
console.log(b1);
 
// counter 
function counter(num1) {
    let c = num1;
    function count() {
        c = c + 1;
        return c;
    }
 
    return count;
}
 
var a = counter(2);
console.log(a());
console.log(a());
console.log(a());
console.log(a());
 
var b = counter(100);
console.log(b());
console.log(b());
console.log(b());
console.log(b()); 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s