JavaScript Closures with Examples Explained
First, let’s take a look at what the documentation says
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. MDN
Lexical Environment
This is just fancy talk for “What do words mean”. When we write code we give words special meaning like: myLuckyNumber = 5
, the word myLuckyNumber
means now 5. But we are not done yet, due to scoping words can mean different things depending on the context/scope.
In the global scope myLuckyNumber
is 5, but within our main
function myLuckyNumber
is 10. We redefine what myLuckyNumber
means in the main
context but leaving the outer myLuckyNumber
alone.
Closure
The most important catchphrase here is: “closures are created every time a function is created, at function creation time.”
Every function has closure and it is created when the function is created (when the function is defined).
Our example from above, but this time myLuckyNumber
gets not defined inside main
but just outside of it. Inside main
we are using myLuckyNumber
so javascript packs this value for us and bundles it with the function. You can see this in the Developer-Tools if you run the following
Open the developer tools in your browser and copy-paste this code in the console. You will see in the debugger panel on the right side under scope one new entry: Closure
We can see Global makes reference to window and Local has just one value (by default) this
which also has a reference to window.
To get a feeling for this, I can just recommend you to place the debugger
statement in various places and see it yourself.
I will write more about debugging in future so stay tuned
The thing with closures is you have probably used them already uncountable times, but when you are conscious about them you can prevent bugs and it helps design good code.
Examples
Privat Values
You may saw this example already on the mdn page I linked above. We can use closures to create private values. We make sure no one can change _privatCounter
directly. We control how this value can be updated. And how it is incremented. For users of our counter, it is not possible to do _privatCounter = 5
they need to use our methods.
Simpler APIs
“Simpler” means simpler to use, not to create… So this pill might be hard to swallow, don’t panic if you don’t understand it. Put yourself a timer and come back later.
Imagine we have an application that supports multiple languages. We might build a small function that can do the translations for us. Something like translate("de", "apple") // -> "apfel"
and fair enough this gets the job done. But we probably just need to set the language one time. 🤔
Function parameters of an outerFunction
become part of the closure for the innerFunction
, in our case lang
will be accessible. And because lang is from within the closure scope and not in the global one, we can create multiple translation functions (en
and de
).
The MDN docs have much more examples https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
I hope this helped… if not please tell me in the comments what could be improved, I’m used to teaching in front of a class, so I’m used to instant feedback. That's why writing feels strange to me 😅
Cheers.