Closures

A closure refers to the lexical context a function was declared in and the variables it has access to. Closures allow us to dynamically create functions, implement encapsulation, and create interfaces to interact with our code. Learn how to use them to perform each of these tasks.

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.

Get hands-on with 1000+ tech skills courses.