Closures in Javascript with 3 Simple Examples | Revive Coding

In JavaScript, a closure is a function that has access to the variables in the scope in which it was defined, even after the outer function in which it was defined has finished executing.

This allows the inner function to remember the state of the outer function and access the variables in its scope even after the outer function has been completed.

Here are three simple examples of closures in JavaScript:

A simple function that creates and returns a function that adds a specified number to a given number:

function createAdder(x) {
return function(y) {
return x + y; } }
const add5 = createAdder(5);
console.log(add5(10)); // 15

In this example, the createAdder function creates and returns an inner function that adds the value of x (which is passed to createAdder as an argument) to a given number.

Because the inner function has access to the x variable in the scope of the createAdder function, it can "remember" the value of x even after the createAdder function has finished executing and use it to add to the number that is passed to it.

A function that creates and returns a function that keeps track of how many times it has been called:

image.png

In this example, the createCounter function creates and returns an inner function that increments a count variable each time it is called.

Because the inner function has access to the count variable in the scope of the createCounter function, it can "remember" the current value of count and update it each time it is called, even after the createCounter function has finished executing.

A function that creates and returns a function that maintains a private list of items:

image.png

In this example, the createList function creates and returns an object with two methods: addItem and getItems. The addItem method adds a new item to a private items array, while the getItems method returns the current list of items.

Because the methods have access to the items array in the scope of the createList function, they can "remember" the state of the array and update or retrieve it even after the createList function has finished executing.