Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Javascript Closure?
2.1.
Example
2.2.
Javascript
3.
JavaScript Closures and Loops
3.1.
Javascript
4.
When to Use Closure in JavaScript?
5.
Examples of Closure in JavaScript
5.1.
Example 1: Counter Using Closure
5.2.
Javascript
5.3.
Example 2: Function Factory
5.4.
Javascript
6.
Closure scope chain
7.
Frequently Asked Questions
7.1.
What is a closure in JavaScript?
7.2.
What is the difference between closure and callback in JavaScript?
7.3.
What is disadvantage of closure in JavaScript?
7.4.
What is currying and closure in JavaScript?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Javascript Closure

Author Ravi Khorwal
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

JavaScript closures are a fundamental concept in the JavaScript programming language, allowing functions to have access to the scope in which they were created. Closures are vital in modern web development, enabling encapsulation and the management of state in an application, thereby solving real-world problems like data privacy and code modularity.

Javascript Closure

In this blog, we will learn about JavaScript closure. We will learn about core concepts, real-world applications and much more. 

What is Javascript Closure?

A closure in JavaScript is a function that retains access to variables from its outer (enclosing) scope even after that scope has finished executing. It "closes over" the variables it needs, preserving them and allowing the function to access and manipulate those variables, even when invoked outside their original scope.

Example

Let us take an example to understand closure.

  • Javascript

Javascript

function outer() {
let outerVar = 'I am from the outer function';
function inner() {
console.log(outerVar);
}
return inner;
}
const closureExample = outer();
closureExample();

Explanation:

In this example, the inner function is a closure. It's defined inside the outer function and has access to the outerVar variable even after outer has finished execution. When closureExample() is called, it prints the value of outerVar. 

Output:

output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

JavaScript Closures and Loops

Closures work seamlessly with loops in JavaScript. However, developers need to be cautious about the closure's reference to variables and their values due to asynchronous behavior in loops. Let us try to understand with the help of an example:

  • Javascript

Javascript

for (var i = 1; i <= 3; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}

Explanation:

This example will produce output 4 three times because the loop has finished before the setTimeout executes.

Output:

output

When to Use Closure in JavaScript?

We can use closure in JavaScript in several scenarios such as:

  • Data Encapsulation: Closures are useful when you want to encapsulate data within a function and expose only necessary functionality. This helps in creating private variables that are inaccessible from outside the function.
  • Callback Functions: Closures are commonly used in callback functions where you want to maintain access to the variables of the outer function even after it has completed execution.
  • Functional Programming: When working with functional programming concepts, closures can be employed to create higher-order functions or curry functions.
  • Event Handlers: Closures are often used in event handlers to retain access to variables when handling asynchronous events.

Examples of Closure in JavaScript

Let us try to understand closure in JavaScript with the help of different examples:

Example 1: Counter Using Closure

  • Javascript

Javascript

function createCounter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}

const counter = createCounter();
counter();
counter();
counter();

Explanation:

In this example, createCounter is a function that returns another function. The inner function, even after being returned and executed outside its original scope, still has access to the count variable due to closure. This enables the creation of independent counters with their own private count.

Output:

output

Example 2: Function Factory

  • Javascript

Javascript

function greetingGenerator(greeting) {
return function (name) {
console.log(`${greeting}, ${name}!`);
};
}

const greetHello = greetingGenerator('Hello');
const greetGoodMorning = greetingGenerator('Good morning');

greetHello('John'); // Outputs: Hello, John!
greetGoodMorning('Alice'); // Outputs: Good morning, Alice!

Explanation:

In this example, greetingGenerator is a function that takes a greeting as an argument and returns another function. The returned function, when invoked with a name, prints a personalized greeting. Each instance of the returned function holds its own unique greeting due to closure, allowing the creation of different greeting functions.

Output:

output

Closure scope chain

In JavaScript, the closure scope chain refers to the lexical scope chain created by a closure. A closure is a function that has access to variables from its outer (enclosing) scope even after that scope has finished executing. The closure scope chain consists of the chain of scopes that the closure has access to.

When a function is defined inside another function, it forms a closure, and it "closes over" the variables from its outer function. This creates a scope chain where the inner function has access to its own scope and the scopes of all its outer functions.

Frequently Asked Questions

What is a closure in JavaScript?

A closure is a function that captures and remembers the lexical scope in which it was created. It allows the function to access variables from its outer scope even after that scope has finished executing.

What is the difference between closure and callback in JavaScript?

Closure is a function with access to variables from its lexical scope. On the other hand Callback is a function passed as an argument and executed later.

What is disadvantage of closure in JavaScript?

The main disadvantage of closure is that it can lead to memory leaks if not managed properly. Variables in the outer scope are retained even if not needed.

What is currying and closure in JavaScript?

Currying involves creating a chain of closures to transform a function with multiple arguments into a sequence of functions with one argument each.

Conclusion

JavaScript closures are a powerful feature of the language, enabling developers to write more maintainable, modular, and secure code. Their ability to encapsulate state and provide private scopes makes them an indispensable tool in modern web development, ensuring the robustness and reliability of web applications across various domains

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Happy Learning!

Previous article
Lodash _.findIndex() Method
Next article
What is Lodash?
Live masterclass