DEV Community

Bipon Biswas
Bipon Biswas

Posted on

JavaScript Closure

What is a Closure?

A closure is a function having access to the parent scope, even after the parent function has closed. Closures in JavaScript is a feature where an inner function has access to the outer function's variables.

A closure has three scope chains

  • Has access to its own scope [the variable defined within it's curly]
  • Has access to the variables of the outer functions
  • Has access to the global variables
var a = 10;
        function first_func(){
            var b = 20;
            function second_func(){
                var c = a+b;
                return c;
            }
            return second_func();
        }
        var sum = first_func();
        document.write("The sum is " + sum + '<br>')
Enter fullscreen mode Exit fullscreen mode

Closure result

function temporary(){
            let counter = 0;

            return function(){
                counter +=1;
            }
        }
        const add = temporary();
        console.dir(add)
        add();
Enter fullscreen mode Exit fullscreen mode

Output
Image description

function temporary(){
            let counter = 0;

            return function(){
                // counter +=1;
                console.log("Death Closure")
            }
        }
        const add = temporary();
        console.dir(add)
        add();
Enter fullscreen mode Exit fullscreen mode

Output
Image description

Top comments (0)