Javascript Closures: What Are They and Why Are They Important?

Matt Lazewski
The Startup
Published in
4 min readDec 3, 2020
Computer Code

Even if you have only started learning javascript, there is a good chance you have seen or even written a closure yourself. You may just not have realized it. Without a little help, you may end up like me and be in the middle of your first mock technical interview and be perfectly capable of writing and describing what is happening in a closure without knowing what it is called.

Scope

To really understand closures, you first need to understand scope. In javascript, there are two types of scope: global and local. Global variables are declared outside of a function and are accessible at any point in the program. Global variables are widely considered to be bad practice as they can lead to issues as an application grows. Local variables are declared within a function, hence they are local to that function. They can only be used within the scope of that function.

let global = "this is a global variable";
function localVariable() { let local = "this is a local variable"; return local;};
console.log(global) <--- returns "this is a global variable"console.log(localVariable()) <-- returns "this is a local variable"console.log(local) <-- returns ReferenceError: local is not defined

As we can see, global is accessible throughout. If we wanted to, we could even access it inside of our localVariable function. Local, on the other hand, is only accessible within our localVariable function, when we try to call it outside of the function we are given an error.

Closures

Now that we are experts on scope, we can now understand the power of closures. The idea behind closures is that we create a function containing its own variables and scope, then within that function, create another function with its own variables and scope. The variables within that second function are only accessible via the the first function. Let’s take a closer look.

function sayHello() { let greeting = "Hello"; return function greet(){   let name = "Matt"   return greeting + " " + name  };};let greetFriend = sayHello() // attaches the outer function 
console.log(sayHello()) // returns [Function: greet]console.log(name) //returns ""console.log(greetFriend()) //returns "Hello Matt"

In the function above. We declare the outer function sayHello with the variable greeting. We then return a second function with its own variable name, then we put them together to return “Hello Matt”. As we can see if we try to return name as a global variable we get nothing back. Our global scope has no idea what name is. We can also see that if we try to return our sayHello function, it only returns to us our inner function. This is where we see the true magic of closures. Once we attach the sayHello function to a variable, we are then able to call that variable as a function and have access to the inner function, greet, and can be return the phrase “Hello Matt. The function returned a value that referenced something from outside the scope.

Let’s take this one step further. Say you want to create an object, and each instance will have many properties. Maybe you do not want global access to each property. Maybe, for example, one property is some form of password. We can use closures to protect that property.

function bankAccount() {  let correctPinNumber = "1234"  return {    name: "Matt",    pinNumber: function(pin) {      return pin === correctPinNumber ? "Success" : "Incorrect Pin"    }  }}let personOne = bankAccount()console.log(personOne.pinNumber("4567")); // returns Incorrect Pinconsole.log(personOne.pinNumber("1234")); // returns Success

Here we have a function, bankAccount, that has one variable, correctPinNumber. This function returns an object with two properties, name and pinNumber. PinNumber calls a function that takes in one argument, pin, which returns either “Success” or “Incorrect Pin”, based on user input. We then assign our outer function to a variable, which gives us access to our anonymous function inside of our object. As we can see, our response will differ depending on what we pass in as our argument. Now even though I would never recommend doing this to protect user information, it shines light on just how powerful closures can be.

Closures, although not entirely essential to all applications, can provide developers with cleaner, more organized code that can maintain local scope and keep access to certain variables restricted from the rest of the application. While knowing and utilizing them may not land you a top tech job, it may just be that one missing piece that’s keeping you from nailing that technical interview.

--

--

Matt Lazewski
The Startup

Rookie coder trying to find my way into the tech world.