DEV Community

Bipon Biswas
Bipon Biswas

Posted on

2 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)