What is a Closure, Anyway?

omwri
2 min readFeb 11, 2020
Photo by MEAX on Unsplash

It may seem like a song by the Chainsmokers, but it is a simple concept to understand.

A closure in JavaScript is a functionality provided by the language wherein an inner function is enclosed inside an outer function, and the inner function has access to the variables in the lexical scope of the outer function.

In plain English, a closure allow some code to do stuff while remembering and using the stuff that’s above it.

Still confused?

Okay, let’s see some examples to really illustrate what closures are and how they can be used.

Creating Modules

By using a closure,you can return an object with functions as seen below.

const assert = require(“assert”);const listMaker = (list) => {
return {
add: (item) => list.push(item),
getList: () => list
}
}
const fruitListMaker = listMaker([“Apple”, “Banana”]);fruitListMaker.add(“Orange”);assert.deepStrictEqual(fruitListMaker.getList(), [“Apple”, “Banana”, “Orange”])

Here, the listMaker() takes an initial seed list array and then returns an object that can operate upon it.

Data Hiding

Using closures, you can enclose private variables inside the outer function.

Then, you can return an inner function that operates using the private variable. This private variable is unexposed to the external world but can still be used via a returned function.

const assert = require(“assert”);const addSecretNumberTo = baseNumber => {  let secretNumber = 20;  return () => baseNumber + secretNumber;}const addSecretNumber = addSecretNumberTo(20);assert.equal(addSecretNumber(), 40);

This technique can, for example, be used to create hashing and salting methods.

Creating Partial Functions

By using closures, a developer can create a wrapper function that returns another function. This function can then be used to operate on data.

For example, let us consider the following code.

const assert = require(“assert”);const multiplyBy = multiplicand => {  return multiplier => multiplicand * multiplier}const multiplyBy10 = multiplyBy(10);assert.equal(multiplyBy10(5), 50)

Here, the function `multiplyBy`creates a closure. The value of the multiplicand is accessible by the inner function.

As we look at the operation of the code, first, the function multiplyBy(10) is called, which returns a function multiplyBy10. When we call the function multiplyBy10 with the value 5, the value 10 is “remembered” by the external function. Hence, the operation turns into 5 multiplied by 10, and the value returned by this operation is 50.

So, there you go. Closures in all their glory. They are a powerful technique to help keep your code readable, reusable, and reasonable. So take this knowledge and go forth and build awesome things.

--

--