A closure is a combination of a function bundled together (enclosed) with references to its surrounding state. In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Consider the following example code:

creates a local variable called and a function called . The the function is an inner function that is defined inside and is available only within the body of the function. Note that the a function has no local variables of its own. However, since inner functions have access to the variables of outer functions, can access the variable declared in the parent function, .

let see below an example of closure:

In this example, we have defined a function lastname, which takes a single argument last, and returns a new function. The function it returns takes a single argument first, and returns the concation of “first” and “last”.

lastNameLee is closure here. It shares the same function body definition. In lastNameLee's a lexical environment, last is “lee”. So when we call lastNameLee function although it doesn't access to first directly the first variable is global for lastNameLee. So it can access the first variable as it is declared in the parent function



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store