Explain it like I'm 5 - JavaScript Closures
If you write JavaScript for a while you will inevitably hear about closures. You can get really far without knowing what a closure actually is. In fact, if you write your code well, you never really need to know how a closure works...
That said, it is a key concept to how JavaScript actually operates. And it is almost definitely an entry level interview or college question. So, what is a closure?
What is a closure?
A closure is a function and the variables it can access from its lexical scope. A lexical scope is the variables defined around around a function when it is created, consider the following example:
function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // prints 1 counter(); // prints 2
This is a simple example of a closure, even though count is not defined in inner
, since inner
is part of outer
it encloses the space and has access to the count
variable as well, even after the outer
function has finished executing.
Woohoo! Closures!!
A note on variables
Before modern JS (pre-ES6) JavaScript variables were declared with var
. A var
is either global scoped or function scoped. This makes it tricky if you try to declare a variable in a condition, for example:
if (someCondition) { var x = true; } else { var x = false; } console.log(x); // x still exists in this enclosure
With ES6, you can declare variables with let
and const
. These declarations use block scoping which includes conditionals and loops. This is similar to other languages like C and Java and makes the closures easier to manage.
let y; // must declare in outer scope if (someCondition) { const x = true; y = true; } else { const x = false; y = false; } console.log(x); // x only exists in the conditional closure console.log(y); // y exists because it was defined in the same scope
I hope this helped you understand closures!
Enjoyed this article? Subscribe to the RSS Feed!