What are Closures?

The Closures occur in JavaScript when a function “remembers” its lexical scope even if it’s executed the outside that scope. In other words, a closure allows a function to access variables from its containing function and even after the containing function has finished executing.

Example: In this example, a closure is created where the inner function retains access to the “name” variable from its containing “outers” function, allowing it to display a personalized greeting when invoked.

Javascript




function outers() {
    let name = "Kumar";
    function inner() {
        console.log("Hello, " + name + "!");
    }
    return inner;
}
let greeting = outers();
greeting();


Output:

Hello, Kumar!

Difference Between Scope and Closures in JavaScript

The scope and closures are fundamental concepts that play a crucial role in how variables are accessed and managed within the functions and blocks of code. In this article, we will learn about the difference between scope and closures in JavaScript.

Similar Reads

What is Scope?

The Scope in JavaScript refers to the context or environment in which a variable or function is declared and can be accessed. JavaScript uses function-based scope meaning variables declared inside a function are locally scoped in while variables declared outside any function have global scope....

What are Closures?

...

Difference between scope and closures in JavaScript:

The Closures occur in JavaScript when a function “remembers” its lexical scope even if it’s executed the outside that scope. In other words, a closure allows a function to access variables from its containing function and even after the containing function has finished executing....