Closure in Javascript

Berel Levy
4 min readOct 18, 2020

what is closure? There’s a short answer and a long answer.

The short answer is: read the long answer.

Long Answer

You know how variables declared inside a function disappear once the function is done? Weeeellll… that doesn’t always happen. and here’s why.

You’re dead if nobody knows you

first let’s understand why those variables disappear. JavaScript has something called garbage collection. Garbage collection is a very descriptive and un-technical name for the rules JavaScript follows to free up memory used by variables. One of the rules of garbage collection is that once a variable is not referenced by any other code it is trashed, well, removed from memory, but ‘trashed’ has more emotion. The life of a variable is fickle, indeed.

we might now be able to understand why variables defined inside a function will disappear once the function is done. Since no other code has access to that inner scope, we can assume that no other code references that variable.

We can also make a nice, simple rule and assume that there is no way any code outside a function can ever reference a variable inside a function, right? Right???

Wrong.

Let’s remember two other quirks that come with our beloved JavaScript; Lexical Scope and First-Class Functions. While we won’t deep dive into these concepts right now, let’s try to summarize them accurately.

  1. Lexical scope: Functions have access to variables defined in their outer scope.
  2. First-Class Functions: Function definitions (and uninvoked ones at that!) can be passed around like regular data.

Suppose we define a function, let’s name it mommy,

function mommy() {

}

Inside this function we define another function, we’ll name it baby,

function mommy() {
const baby = () => {
console.log('kick!')
}

}

But we don’t invoke baby, instead, we return this inner function from the outer function.

function mommy() {
const baby = () => {
console.log('wah!')
}
return baby
}

So now, when we assign the return value of the mommy function to a new variable, let’s call it baby as well,

function mommy() {
const baby = () => {
console.log('wah!')
}
return baby
}
let baby = mommy()

Why? because the return value of mommy is the ‘baby’ function definition. so this new variable outside of mommy contains the function that was defined inside of mommy.

function mommy() {
const baby = () => {
console.log('wah!')
}
return baby
}
let baby = mommy()
baby()
// -> 'wah!'

Suppose, before we defined baby, we defined another variable name ‘a’, and we assigned it the value of 0.

function mommy() {
let a = 0
const baby = () => {
console.log(a)
}
return baby
}
let baby = mommy()

Quick question, does baby have access to this variable? yes. one more question, when we return the baby function from the mommy, and assign it to a variable that is outside of mommy, does it still have access to the a variable a defined inside mommy?? YES.

function mommy() {
let a = 0
const baby = () => {
console.log(a)
}
return baby
}
let baby = mommy()
baby()
// -> 0
// 🤯

One last question, suppose, inside our baby function, we made changes to the variable ‘a’ that is inside mommy, would those changes stick around even if we call baby once it’s outside mommy?? Would they stick???

function mommy() {
let a = 0
const baby = () => {
console.log(a)
a++
}
return baby
}
let baby = mommy()
baby()
// -> 0
baby()
// -> 1

Yes, yes! A thousand times yes!

That mind twister is closure. Since the baby function has access to the variable ‘a’ and references it, the garbage collector doesn’t trash it! and the mommy function doesn’t finish running. Our baby now has access to the variable a for as long as baby is alive. baby can call it, change it and play with it as much as we like. If you think of assigning the return value of mommy to a variable as birth, you can think of closure as not cutting the umbilical cord.

Why ever use closure???

The first reason is that once you are comfortable with closure it becomes a great tool to encapsulate functionality in a concise way.

The second reason is that it makes you look smart and the technical job market is getting very competitive. demand for a product or service usually increases before the supply increases, then the supply catches up to demand, and then supply surpasses demand. At first there was a strong demand for coders, and there weren’t enough of us, then bootcamps exploded all over the place and there were enough coders, then of course along the way everybody heard that coding is a great profession so now everyone and their cousin wants to be a coder, so there are too many coders. We need to differentiate ourselves, first by writing blogs to show that we are passionate, then by using closure to show that we are smart, then writing blogs about closure to show that we are smart, passionate, and just a little sarcastic too.

I hope this blog had you giggling, or smirking, or even rolling your eyes, because remember, you’re dead if nobody knows you.

--

--

Berel Levy

Experienced software engineer and data engineer who enjoys the finer things in coding.