JavaScript Closures

A closure is a function that can access the scope of its parent function even when the parent scope has been closed. The scope of a function is closed when the function has finished when the function has been completed. Closures can be explained through an example of creating a simple counter.

The below code shows a function that increments a ‘count’ variable. However, the problem with this code is that the ‘count’ variable is within the global scope, which means other code can access the ‘count’ variable and change it. This reduces the integrity of the ‘count’ variable, as we cannot be sure where exactly the ‘count’ variable has been changed within the code.

We can solve the scope problem by putting the count variable within the function. This means that the ‘count’ variable will not be available outside of the function. However, this causes another problem, the count variable will always result in the value 1 as it is being set to 0 every time the function is called.

So we need a way to only initialise the count variable once but also keep the accessibility of the ‘count’ variable private. This is where closures come in. A closure in JavaScript can be described as a self-invoking function that also returns a function. The code below shows a closure and can be quite complicated to understand all at once. To begin with, we have a variable called ‘add’, the other side of the equals sign is a function wrapped in parenthesis. This function is invoked, or called, as there are two parentheses at the end of the code. This is the same as calling any other function, we pass the parameters within parenthesis after the function. This is a self-invoking function. Inside this function, a ‘count’ variable is set to 0, and then a function is returned. The variable we started with, called ‘add’, is assigned the value of the returned function, the child function. The child function is still able to access the scope of the parent function, even though the scope is closed.

This means, the ‘count’ variable is not accessible outside of the function, and the value of the count will increment every time the ‘add’ function is called.

Leave a Reply