What is closure in Javascript - Free Web Development || UI Development || React JS || Angular

Latest

Free Web Development ||Free UI Development || React JS || HTML5 || CSS3 || JavaScript || Angular Learn Web Development || Frontend Developer || Full Stack Developer

1 / 3
Welcome to Shravan Ghanchi

Sunday, April 6, 2025

What is closure in Javascript

Definition: A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing. It allows functions to maintain private states and avoid polluting the global scope.

How Closures Work: When a function is created inside another function, the inner function retains access to the variables of the outer function—even after the outer function has completed execution.


Code Example: 

function outerFunction() {

    let counter = 0;  // Variable inside outer function

    return function innerFunction() { 

    counter++; 

// Inner function modifies the outer variable

console.log(counter);

    };

}

const increment = outerFunction(); 

// Calls outerFunction and gets innerFunction

increment();  // Output: 1

increment();  // Output: 2

increment();  // Output: 3


Even though  has finished executing, the returned  still retains access to , forming a closure.

Real-World Use Cases : Closures are useful in

Functional Programming: Passing behavior dynamically.

Memoization: Caching function results to improve performance.

Event Handlers: Retaining references for handling UI events in frameworks like React.

Encapsulation & Data Privacy: Keeping variables private within functions.

No comments:

Post a Comment

Snow
Forest
Mountains
Snow
Forest
Mountains