DEV Community

Anandhi P
Anandhi P

Posted on

JavaScript Closures

JavaScript Closures

“Closure means an inner function remembers the outer function's variable.”

A closure is a function that remembers variables from its outer function.

Example
function outer() {
let message = "Hello";

function inner() {
    console.log(message);
}

return inner;
Enter fullscreen mode Exit fullscreen mode

}

let result = outer();
result();

Output

Hello
Explanation

The inner() function can access the message variable from the outer() function. Even after outer() finishes, inner() remembers the message variable.

JavaScript Closures – More

  • Closure is created when a function is created inside another function.
    • The inner function can access the outer function's variables.
    • The inner function remembers those variables.
    • The outer function finish aanaalum, closure variables remain accessible.
    • Closures are useful for data privacy and maintaining state.

Top comments (0)