JavaScript Closures Explained in 3 Minutes
Closures in JavaScript tend to seem more difficult than it actually is. The essence is basically the following:
Closures enable functions to remember their surroundings.
More specifically: sometimes a function will need to remember the variables from the scope it was created in. It will do so with the help of a closure.
This is only relevant when a function is defined within another function.
A simple example
Let’s learn it through an example.
PS: If you’re more of a visual learner, take a look at the Scrimba screencast I’ve embedded below, which walks through the code from this article.
Take a good look at the code snippet below, and make sure you understand it:
function outerFunction(){ var message = 'howdy'; function greet() {
console.log(message);
} return greet;}
If we now try to console.log the message
variable below this code, we’ll get undefined, as message
is a private variable of the outerFunction
’s scope, so you can not access it outside it scope.
console.log(message);
=> 'undefined'
However, we can call outerFunction()
, which will return the greet
function, and then store the result in the outerGreet
variable.
var outerGreet = outerFunction();
When we then call outerGreet()
, we magically get access to the message
variable again, as we can see it being logged into the console.
outerGreet();
=> 'hodwy'
This is possible thanks to a closure, as the greet function remembered the surroundings it was created in. If the greet
function was a person, it would think the following when it was created:
Hm…. My job is to log out the message variable. However, this variable isn’t defined within myself, but outside of myself. So I better remember it, so that I can use it later on, when I’m no longer in the same surroundings as I’m right now.
Peaking at the closure
The above concept might seem a bit abstract. However, it’s actually very concrete. Let’s peak into our greet
function and have a look at the closure.
In the image below, I’ve pasted the code above into the console of a web page, and then accessed the outerGreet.prototype
.
We’ll find the closure within a key called [[Scopes]]
.
The first scope is called Closures
. It also mentions in parenthesis which scope it remembers the variables from: the outerFunction
. And as you can see: it remembers a variable message
which has the value howdy.
There are of course more things to learn about closures, but this is the core idea.
Thanks for reading! My name is Per, and I’m the co-founder of Scrimba, a tool for creating interactive coding screencasts. Do check it out if you’re interested in learning more about web development!