What is a Closure in JavaScript?

ยท

2 min read

If you've been developing in JavaScript for any period of time you would have come across the term closure. But what does that mean in practical terms?

Let dig into it.

Closure put simply

In simple terms a closure is when a function accesses a variable that is outside of it's own scope.

This is quite different to how functions operate in many other programming languages. Usually you will have a function, and this function can only access variables within its own scope. However, in JavaScript, a function can access variables from it's parents.

Let's look at a simple example:

const myName = "Michael"

function printName() {
  console.log(myName)
}

printName()

As you can see from the above example, the printName function can access the myName variable even though it is not within it's scope but actually comes from it's parent.

How do closures work in JavaScript

In JavaScript, every scope has access to everything outside of its scope. The example we talked about above is one possible way of using closures, but it is not the most common way of using closures in modern JavaScript.

When we think of closures in modern day JavaScript we are normally talking about a function inside of other functions. Let's take a look how:

function myApp(variableOne) {
  return function printVariable(variableTwo) {
    console.log("One: " + variableOne)
    console.log("Two: " + variableTwo)
  }
}

const myFunc = myApp("Hi")
myFunc("There")

The output from the above will be:

One: Hi
Two: There

variableOne is only available when myFunc is being executed. Even when myApp has finished executing, myFunc will still have access to variableOne. This is where closures come into their own.

What happens when we create myFunc is that variableOne is saved and then when myFunc is run, variableOne can be used and is logged out to the console.

The most common usecase for this often times is to have variables that we pass into functions that can be used in other functions.

Let's say for example you want to trigger off a function when clicking a button:

function buttonClicked(id) {
  const myName = "Michael";

  return function displayName() {
    console.log(id + " is clicked, welcome " + myName);
  };
}

const youClickedMe = buttonClicked(100);
youClickedMe();

The output from the above will be "100 is cliked, welcome Michael".

As you can see from the above, closures can be useful when passing variables down to functions within functions.

Hopefully you found this article helpful, please follow for more like this in the future.

Until next time ๐Ÿ™‹โ€โ™‚๏ธ.

Did you find this article valuable?

Support Simplifying Code by becoming a sponsor. Any amount is appreciated!

ย