JS: What Is A Closure?

Elizabeth Kim
2 min readJun 21, 2020

--

This is another common question asked in technical interviews relating to Javascript.

According to the MDN docs, a closure is a combination of a function bundled together with references to its surrounding state. Simply put, a closure is a function enclosed inside the outer function and has access to its local variables that were in-scope at the time it is created.

In Javascript, a closure is called everytime the function is called at the function’s time. Using an example from Eloquent Javascript:

In this example, twice is a closure. It creates a lexical environment where the factor parameter is 2. The function value it returns is stored in twice. When this closure is called, it remembers the environment created and multiplies it’s argument, in this case 5, by 2.

If a different variable was created calling on the multiply function, then this would also be a closure; sharing the same function body as the variable twice, but it has a different lexical environment.

A function value is thought of as having both the function in the body and the environment where it is created. When the function value of a closure is called, the function body sees the environment where it is created, not where the environment it is called. Referring back to the example, console.log calls on the variable twice with a number parameter of 5. Because twice is a closure, the function value that was returned from the closure is called with the number parameter of 5 resulting in 10.

Closures give the ability to treat functions as values and frees from the endless bindings that may occur otherwise. A closure relieves the idea that there is a chain effect of bindings. After a local binding is created, it can used again, or a new local binding can be created without relating to a local binding created before.

--

--