Coding Ninjas Logo

Home > JavaScript Questions > What do you understand by Closures in JavaScript?

Q: What do you understand by Closures in JavaScript?



Answer:

Closures provide a better, concise, creative, and expressive way of writing code for JavaScript developers and programmers. Technically speaking, closures are a combination of lexical environment and function.

In other words, a closure is a locally declared variable that is related to a function and stays in the memory when the related function has returned. All local variables that were in-scope at the time of the closure creation are contained by the closure.

Following code snippet demonstrates using a normal function in JavaScript:

    
        function greet(message) {
            console.log(message);
        }
        function greeter(name, age) {
            return name + " says Hey!! He is " + age + " years old";
        }
        var message = greeter("Akhil", 26);
        greet(message);
                        

The aforementioned function can be represented in a better way by using closures. This is demonstrated in the following code snippet:

    
        function greeter(name, age) {
            var message = name + " says Hey!! He is " + age + " years old";
            return function greet() {
            console.log(message);
            };
        }
    

// Generate the closure

    
        var AkhilGreeter = greeter("Akhil", 26);
    

// Use the closure

    
        AkhilGreeter();
    

//or alternatively you can call it in a single line using

    
        greeter("akhil", 28)();
    

Similar Questions