---
title: "Working of closures in JavaScript ?"  
description: "Working of closures in JavaScript ?"  
author: "Steilla Mitchel"  
published: 2023-07-21  
updated: 2023-07-21  
canonical: https://www.mindstick.com/forum/159193/working-of-closures-in-javascript  
category: "javascript"  
tags: ["javascript", "javascript library"]  
reading_time: 2 minutes  

---

# Working of closures in JavaScript ?

Working of closures in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript) ?

## Replies

### Reply by Aryan Kumar

A closure in JavaScript is a function that has access to the variables in its enclosing scope, even after the enclosing scope has been closed. In other words, a closure is a function that "remembers" the variables from the scope in which it was created, even after that scope has been destroyed.

Closures are created when a function is created within another function. For example, the following code creates a closure:

```plaintext
function outerFunction() {
  var name = "John Doe";

  function innerFunction() {
    console.log(name);
  }

  return innerFunction;
}

const innerFunction = outerFunction();
innerFunction(); // "John Doe"
```

In this code, the `outerFunction()` function creates a closure by creating the `innerFunction()` function within its scope. The `innerFunction()` function has access to the `name` variable from the `outerFunction()` scope, even though the `outerFunction()` function has already been executed.

Closures can be used to create reusable functions that can access data from other functions. For example, the following code creates a closure that can be used to get the current user's name:

```plaintext
function getName() {
  var name = localStorage.getItem("name");

  function getUserName() {
    return name;
  }

  return getUserName;
}

const getUser = getName();
console.log(getUser()); // "John Doe"
```

In this code, the `getName()` function creates a closure that returns the `getUserName()` function. The `getUserName()` function has access to the `name` variable from the `getName()` scope, even though the `getName()` function has already been executed.

The `getUser()` function then calls the `getUserName()` function to get the current user's name.

Closures are a powerful tool that can be used to create reusable and efficient JavaScript code.


---

Original Source: https://www.mindstick.com/forum/159193/working-of-closures-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
