Monday, 10 December 2018

JavaScript: Explain about closures

A closure is an inner function that remembers its outer variables and can access them.

A closure can able to access
a.   variables defined in its scope
b.   variables defined in outer function.
c.   Global variables.

I feel, you can understand about closures better via examples. So I am providing below examples.

Example 1
HelloWorld.js
function foo(x){
    function increment(y){
        return x + y;
    }
    
    if(x % 2 == 0){
        return increment(10);
    }else{
        return increment(-10);
    }
}

var x = foo(10);
var y = foo(-10);

console.log("x : " + x);
console.log("y : " + y);

Output
x : 20
y : 0

Example 2
HelloWorld.js
function foo(x){
    return function increment(y){
        return x + y;
    }
}

var incBy10 = foo(10);
var decBy10 = foo(-10);

var x = incBy10(100);
var y = decBy10(100);

console.log("x : " + x);
console.log("y : " + y);

Output
x : 110
y : 90

foo(10)

returns

function increment(y){
    return 10 + y;
}

Example 3

HelloWorld.js
function welcome(name){
    var msg = "Hello " + name;
    
    function greet(){
        console.log(msg);
    }
    
    greet();
}

welcome("Krishna");

Output
Hello Krishna

Example 4
HelloWorld.js

function welcome(name){
    var msg = "Hello " + name;
    
    var greet = function (){
        console.log(msg);
    }
    
    return greet;
}

var hello = welcome("Krishna");
hello();


Output
Hello Krishna

Example 5: You can even return the object that manipulates the variables of outer function.

HelloWorld.js
function welcome(name){
    var msg = "Hello " + name;
    
    return {
        
        greetMeLower: function(){
            return msg.toLowerCase();
        },
        
        greetMeUpper : function(){
            return msg.toUpperCase();
        },
        
        sayBye : function(){
            return "Good Bye " + name;
        }
        
        
    }
}

var obj =  welcome("Krishna");

console.log(`${obj.greetMeLower()}`);
console.log(`${obj.greetMeUpper()}`);
console.log(`${obj.sayBye()}`);

Output
hello krishna
HELLO KRISHNA
Good Bye Krishna


In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions.



Previous                                                 Next                                                 Home

No comments:

Post a Comment