What are closures and How do I use them?

Dukhyun Ko
3 min readAug 17, 2020

It’s been two weeks since I started learning JavaScript. It’s been really hard trying to grasp all these different terms and syntaxes that I have never encountered before. Then in our lecture, our instructor brought up the topic of closure.

When this closure first came up in the lecture, I instantly thought

‘Wait…..’

I think I’ve been using closures the whole time without realizing that it was called closure. So, I decided to dig in a little bit more into it.

So, what are closures?

“A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.” -from MDN web docs

Cool, so what does this mean? As a newbie in JavaScript, I also had to look up what lexical environment/lexical scope meant. 😅

Lexical Scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope. This means that the child functions are lexically bound to the execution context of their parents. Lexical scope is sometimes also referred to as Static Scope.”
-from Understanding Scope in JavaScript

After reading all these different Medium posts and articles about closures, my understanding for closure is that there are functions and variables declared globally. Then we can lexically assign functions and variables to this global function and this creates a closure. Then assign another function within that function and create another closure. Most important thing about closure is that they have access to the variables and other resources in its parent scope and this means that it is lexically bound.

What’s good about closures?

Closures are not only used in JavaScript, but also widely used in many different languages.

function sayHi(name) {
return function(){
return `Hello ${name}!`
}
}

This is a very basic usage of a closure.

// What will this return??
sayHi("Duke")

Without really understanding how closures work some would assume this would return:

"Hello Duke!" ❌ƒ (){
return `Hello ${name}!` ⭕️
}

Executing sayHi(“Duke”) actually returns the function that was declared inside out sayHi function. So what does this mean? It means that we can use sayHi(name) in many different ways!

let sayHiToEsther = sayHi("Esther")
let sayHiToDad = sayHi("Dad")
let sayHiToMom = sayHi("Mom")
let sayHiToSister = sayHi("Sister")

These sayHiToSomeone variables are actually a function and when we execute them.

sayHiToEsther(); returns "Hello Esther!"
sayHiToDad(); returns "Hello sayHiToDad!"
sayHiToMom(); returns "Hello Mom!"
sayHiToSister(); returns "Hello Sister!"

‘Okay? So what?’ This was my initial thought.
‘Wait…. omg…’ This was me when I realized I was using this kind of concept when I created “helper method” in Ruby. It was hard to think of how to take advantage of closure, but I was using it all along without knowing that it was a closure. Now that I can consciously take advantage of lexical scopes and closures, I can be intentional about using closures and get better at using it in different places.

Some Practical Closures

//using closure to change font size on click.function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

Private Method with Closures

var changeByTen = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(10);
},

decrement: function() {
changeBy(-10);
},

value: function() {
return privateCounter;
}
}
};

var counter1 = changeByTen();
var counter2 = changeByTen();

alert(counter1.value()); // 0.

counter1.increment(); // adding 10 here
counter1.increment(); // adding 10 here
alert(counter1.value()); // 20.

counter1.decrement(); //subtracting 10 here
alert(counter1.value()); // 10.
alert(counter2.value()); // 0.

To learn more please visit:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#:~:text=Practical%20closures,with%20one%20or%20more%20methods.

Please comment below to tell me if I am misunderstanding any part of closure! Thank you.

There’s just so much more to learn and it feels like it will never come to a closure and I’m always learning but never able to come to a knowledge of the truth.

--

--

Dukhyun Ko

Software Engineer 👨🏻‍💻 | Personal Trainer 🏋🏻‍♂️ | Commissioner 🏀