What is a closure?
A closure is the combination of a function bundled with its surrounding state. This means that we can access the scope in which the function is defined, from inside that function. Let's look at a simple example:
Here we have an outer function
add and an inner function
add to a variable will return the inner function
Invoking the variable and passing a number will execute
addFive. At first, it seems accessing
x should not be possible since
x belongs to the scope of the outer function which has already finished executing. But, because the function
addFive forms a closure, it also has access to the environment or scope in which it was declared (also known as the lexical environment).
If a function forms a closure, it can access variables and functions declared in the parent/outer function even after that parent/outer function finishes executing. This principle allows us to implement private variables.
Implementing private variables
This example applies the concept we looked at in the previous section. An IIFE(Immediately Invoked Function Expression) is assigned to the constant
Door. The IIFE executes immediately and returns an object with two methods. This returned object has a function and a variable in its lexical environment.
The IIFE finishes executing, so the variable and function are both inaccessible from the outside. Only the two methods inside the returned object can access them because they form closures.
Top comments (0)