JavaScript Closures

It is an advanced concept of javascript. This is a really interesting concept in javascript. So basically it is a function inside a function which can access outer function properties. According to MDN
“A closure is the combination of a function and the lexical environment within which that function was declared.”

So to understand this you need to understand Function, Arguments, and Scope. Now we need to understand with a basic example –


Basic reprasentation

Basic use of Closure

Example 1

function outer(msg) {

    return function inner() {

        return msg;

var o = outer("I am outer scope msg");
o(); // I am outer scope msg

Example 2

var add = (function () {
    var count = 0;
    return function () { return count += 1; }

add(); // 1
add(); // 2

So now you can see The inner function has access not only to the outer function’s variables but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments to an object, however, even though it can call the outer function’s parameters directly.

Private methods with closures

Example 3

var Cls = (function() {
    var mymsg = "Welcome into closures"; 

    function msg() {
        return mymsg;

    return {
        msg: msg

Cls.msg(); // Welcome into closures

Here you can see Cls is an outer function that is returning an object which is accessing the private function inside the Cls function and msg function also using mymsg private variable. So when we call msg function then we are getting mymsg msg in return for the function.

Sum with closures

Example 4

function sum(a) {

    return function(b) {
        return a + b; // takes "a" from the outer lexical environment

console.log(sum(1)(2)) //3

Here you can see sum is the outer function and in the first case you are passing 1 then you will get the return inner function. Now again you are passing parameter 2 so you are calling the return function and here the previous parameter and current parameter doing an addition operation and at last, you will get the return desired output.

About the Author: Pankaj Bisht