Search⌘ K
AI Features

Closures

Explore how JavaScript closures allow functions to remember their lexical scope even after the outer function finishes. Learn to create dynamic functions with factory functions and understand how closures enable encapsulation to protect data. This lesson helps you write cleaner, more efficient code by using closures to avoid repetition and control access to variables.

We'll cover the following...

Dynamically Generating Functions

Let’s say we want to write a function that lets us add 10 to any number.

function add10(num) {
		return num + 10;
}

We want another function that lets us add 20 to any, and another that lets us add 30, and another that lets us add 40, and 50. Let’s write them.

function add20() {
  	return num + 20;
}

function add30() {
		return num + 30;
}

...

Writing all of these function becomes tiresome and requires a lot of code duplication, something we always want to avoid. We want an easier way to write these functions.

Scope Persistence

When a function is created, it retains access to the scope that it was created in. If it’s created inside another function, it retains access to the scope of that outer function even after that outer function returns.

Javascript (babel-node)
function fnGenerator(str) {
const stringToLog = 'The string I was given is "' + str + '"';
return function() {
console.log(stringToLog);
}
}
const fnReturned = fnGenerator('Bat-Man');
fnReturned(); // -> The string I was given is "Bat-Man"

We’ve just created a closure. MDN defines a closure as

The combination of a function and the ...