Using JavaScript Closures
Damon Marc Rocha II
Posted on July 4, 2020
Recently I completed a mock technical interview. I did pretty well but I missed a few important things that I thought I completely understood. Among these were closures in JavaScript. I knew what a closure was but for some reason could not think of the usefulness of it. In this post, I want to touch on the question I was asked, its answer, and how I followed up to remember the usefulness of closures.
After feeling pretty good answering the first few questions correctly and solving a few coding challenges, I was stumped by this problem:
Using only functions create a method that will return you won on the first call and then for all subsequent calls return sorry you lost.
Now with my Object Oriented Brain, I thought of many ways to do this using objects but did not think of closures. So after struggling with a few different ideas my interviewer walked me through the idea of closures. Then with this knowledge refreshed I easily solved the challenge. I did this by creating a function that returned a nested function. In the outer function, there was a variable that held a boolean value of true; then after the first call to the inner function, it became false. Below is an example of a similar solution
let won = () => {
let won = true
let checkWon = () => {
if (won === true){
won = false
console.log("You Won")
} else{
console.log("You Lost")
}
}
return checkWon
}
let game1 = won()
game1() //=> You won
game2() //=> You lost
game3() //=> You lost
This solution works due to closures. When calling a function inside of another function you have access to all values in the parent function and can change those values. This allows the first function to save certain data based off your interaction with the nested function. After coming to this conclusion I realized that closure was the best option in this case.
So to cement this idea in my head I decided to create a simple calculator. It used a class for calculator operations and closures for rendering, handling events, and storing the entered data until the user wanted an answer. I did this by having the parent function store the entered numbers and operations in a display variable. Then once the user hit enter the display data would be sent to the calculator class to do calculations. This mini-project was a lot easier with closures than using a completely class-based approach.
Here is the repo: Repo
And The Actual Calculator: Demo.
Now please don't be too harsh on me, I know I repeated myself often in my code, but I plan on fixing this once I finish implementing everything. So to sum this all up, do not forget closures because they will come up and can be more efficient than classes in certain cases.
Posted on July 4, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.