PART I: Closures in Javascript

Benyam
3 min readMay 1, 2021

I have seen and heard closure used everywhere but never managed to properly understand what it means.

This blog is meant to serve as a reference for me. You may find some part of it to be too ‘simplistic’ but I hope to leave you with something new too.

The least obvious use case of Closure is with global variables.

In the following code snippet, the variable “catName” is global which is in the entire window or javascript file closure.

const catName="kitty"
function printCatName(){
console.log(catName)
}
printCatName() //kitty

To put it simply, whenever a function manages to access variables outside of its local scope it is highly likely that Closure has come to the rescue.

If you are anything like me you might have assumed that closures are related to anonymous functions. This happens because anonymous functions are common when nesting functions. However, for Closure to work the function does not have to be anonymous.

var outerFunction = function (bar) {    var foo = "foo";    function innerFunction(catName) {console.log(foo + bar + baz +" " + catName);    }//anything defined here is also accessible to innerFunction    var baz = "baz";    return innerFunction;};var bar = "bar";var X = outerFunction(bar); console.dir(X); //[Function: innerFunction]X("kitty ");//foobarbaz KittyX("Milo"); // foobarbaz Milo

Essentially a closure is a function with an extended scope with access to nonglobal variables that aren’t defined inside its body.

In the above example, the innerFunction() has access to variables not necessarily inside of its scope thanks to Closure.

What happens is when invoked outerFunction returns a innerFunction function object or instance. This means this object has access to the foo, bar, and baz variables too. In other words, the function closes over these variables.

The main point to make here is when the outer function finishes running, had it not been for closure, all its variables would have been garbage collected or erased from memory.

In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage or memory occupied by objects that are no longer in use by the program.

As long as the inner function instances i.e. the two X’s are alive their closures make sure foo , bar and baz persist.

One thing worth mentioning is the outer scope does not have to be a function. Here is an example:

const buttonDomElements = document.getElementsByTagName("button");for (let [idx, btn] of buttonDomElements) {   btn.addEventListeneer("click", function onClick() {   console.log(`You clicked on button (${idx})`);   });}

The inner function (onClick) closes over idx and preserves it for as long as the click handler is set on the btn. The closure allows for the click handler to remember the respective idx values of the btn.

In part 2 we will see some advanced concepts around closure.

Any comments and suggestions are welcome.

--

--