Closure

Abhishek Kumar
2 min readJun 17, 2021

--

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:

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

let see below an example of closure:

In this example, we have defined a function lastname(last), 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

--

--