---
title: "What is closure in JavaScript and how does it work?"  
description: "What is closure in JavaScript and how does it work?"  
author: "Revati S Misra"  
published: 2023-04-14  
updated: 2023-11-26  
canonical: https://www.mindstick.com/forum/157806/what-is-closure-in-javascript-and-how-does-it-work  
category: "javascript"  
tags: ["javascript"]  
reading_time: 2 minutes  

---

# What is closure in JavaScript and how does it work?

What is [closure](https://www.mindstick.com/forum/157611/what-is-meant-by-closure-in-javascript-give-an-example) in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript) and how does it work?

## Replies

### Reply by Aryan Kumar

In JavaScript, a closure is a combination of a function and the lexical environment within which that function was declared. A lexical environment consists of the variables that were in scope at the time the closure was created. In simpler terms, a closure allows a function to access variables from its outer (enclosing) scope even after that scope has finished executing.

Here's a breakdown of how closures work in JavaScript:

## Function Definition:

- A closure is created when a function is defined inside another function (the outer function).

## Inner Function Captures Variables:

- The inner function (closure) captures and "closes over" the variables of its outer function, including its parameters and local variables.

## Execution Outside Outer Function:

- Even though **outerFunction** has completed execution, the inner function (**closureFunction**) still has access to the variables from its lexical scope.

## Access to Outer Variables:

- The closure can access and manipulate the variables from the outer function, even though the outer function has finished executing.

In the example above, **innerFunction** forms a closure because it is defined within the scope of **outerFunction**. When **outerFunction** is invoked, it returns **innerFunction**, and the returned function is assigned to **closureFunction**. Even though **outerFunction** has finished executing, **closureFunction** still has access to the **outerVariable** due to the closure.

Closures are powerful in JavaScript and are commonly used for various purposes, including creating private variables, implementing data encapsulation, and managing asynchronous code with callbacks. Understanding closures is essential for writing more advanced and flexible JavaScript code.


---

Original Source: https://www.mindstick.com/forum/157806/what-is-closure-in-javascript-and-how-does-it-work

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
