The Wayback Machine - https://web.archive.org/web/20250110123923/https://www.geeksforgeeks.org/closure-in-javascript/
Open In App

Closure in JavaScript

Last Updated : 17 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A closure is a function that has access to its own scope, the outer function’s variables, and global variables, even after the outer function has finished executing. This enables functions to “remember” their environment.

  • A closure allows a function to access variables from its outer (enclosing) function even after that function has finished executing.
  • Global variables can be made private within a function using closures, ensuring they cannot be accessed or modified directly from outside.
  • Closures provide a way to encapsulate private data and create public methods to interact with it.
  • Closures help retain references to variables that would otherwise be lost after the execution of the outer function.
JavaScript
function outer() {
    let outerVar = "I'm in the outer scope!";
    function inner() {
        console.log(outerVar);
    }
    return inner;
}
const closure = outer(); 
closure(); 

Output
I'm in the outer scope!

In this example

  • outer() defines a local variable outerVar.
  • Inside outer(), we define innerFunction, which logs the value of outerVar.
  • outer() returns inner(), and closure() stores the returned value (which is inner()).
  • Even though outer() has finished execution, inner() can still access outerVar because it “remembers” the environment where it was created. This is the closure at work!

Lexical Scoping

Closures are based on lexical scoping, meaning that a function’s scope is determined by where the function is defined, not where it is executed. This allows inner functions to access variables from their outer function.

JavaScript
function outer() {
    const outerVar = 'I am from outer';

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

    return inner;
}

const newClosure = outer();
newClosure();

Output
I am from outer

In the example above, inner() has access to outerVar because inner was defined inside outer, giving it access to the outer function’s scope.

Private Variables

Closures can encapsulate variables, making them private to a specific function. This is commonly used in module patterns.

JavaScript
function counter() {
// Private variable
    let count = 0; 
    
    return function () {
     // Access and modify the private variable
        count++;
        return count;
    };
}

const increment = counter();
console.log(increment());
console.log(increment());
console.log(increment()); 

Output
1
2
3

Closures and IIFE

IIFEs often leverage closures to encapsulate private state or create modules.

JavaScript
const counter = (function () {
    let count = 0;

    return {
        increment: function () {
            count++;
            console.log(count);
        },
        reset: function () {
            count = 0;
            console.log("Counter reset");
        },
    };
})();

counter.increment(); 
counter.increment(); 
counter.reset();      

Output
1
2
Counter reset

Closure and setTimeout

Closures are often used in asynchronous programming. For example, with setTimeout:

JavaScript
function createTimers() {
    for (let i = 1; i <= 3; i++) {
        setTimeout(function () {
            console.log(`Timer ${i}`);
        }, i * 1000);
    }
}
createTimers(); 

Output:

Timer 1
Timer 2
Timer 3

Closures with this keyword

Closures often lead to confusion when dealing with the this keyword, as this is determined by the execution context, not the lexical scope.

JavaScript
function Person(name) {
    this.name = name;
    
    this.sayName = function () {
        console.log(this.name);
    };

    setTimeout(function () {
        console.log(this.name); 
        // Undefined because 'this' refers to global object
    }.bind(this), 1000); 
    // Fix with bind
}

const G = new Person("GFG");
G.sayName(); 

Benefits of Closures

  • Data Encapsulation: Closures enable data hiding and abstraction.
  • State Management: Retain variables between function calls.
  • Callbacks and Event Listeners: Simplify asynchronous code.

Common Pitfalls

  • Memory Leaks: Excessive use of closures may retain unnecessary references to variables, causing memory issues.
  • Performance Overhead: Overusing closures might lead to larger memory usage due to retained scopes.

Key Takeaways

  • Closures retain access to variables from their parent scope.
  • They are heavily used in functional programming, event handlers, callbacks, and stateful functions.
  • Always be mindful of memory usage when working with closures.

Closure in JavaScript – FAQ’s

Can closures be created in all JavaScript functions?

Yes, closures can be created in any function, but they are most commonly used when a function returns another function.

Why do closures remember their variables?

Closures remember their variables because of lexical scoping—they maintain a reference to the environment in which they were created.

Can closures cause performance issues?

Yes, if closures hold onto large objects or variables that are no longer needed, they can lead to memory leaks.

How can I avoid issues with this in closures?

Use arrow functions or manually bind this to ensure it refers to the correct context in a closure.

Are closures important for asynchronous programming?

Yes, closures are critical for handling asynchronous operations, such as callbacks, promises, and event listeners.



Next Article

Similar Reads

three90RightbarBannerImg