Today, we'll explain how closures work in JavaScript through a simple example.
Understanding closures is crucial for mastering JavaScript as they enable powerful patterns like data privacy and function factories. Furthermore, it’s a common topic in interviews.
Many JavaScript developers struggle with closures due to their abstract nature. We'll explain a clear, simple example to help you grasp them.
Understanding closures to unlock the full potential of your JavaScript skills.
Closures are a fundamental concept in JavaScript, allowing functions to retain access to variables from their containing scope even after that scope has closed.
Code example
We're going to create a function called parentFunction
:
Inside the function, we see the let
variable called num
with a console.log
of it.
We then create a function called childFunction
and return it.
The childFunction
has a console.log
of ++num
. The childFunction
has access to num
because it has access to the scope of its parent function where num
is.
We're going to create a function called finalFunction
by executing the parentFunction
:
If we run the code, here’s how the finalFunction
is:
It's important to note that outside the parentFunction
, we can't access num
. We’ll get an error in the last console.log
of this code:
However, if we execute the finalFunction
:
We see the num
incremented by 1:
We have the first 1 because the first console.log(num)
was executed when the finalFunction
was created through parentFunction()
. And then, 2 is shown because we run finalFunction
.
The finalFunction
has access to num
, even though the parentFunction
has already been called and closed.
If we continue executing the finalFunction
, it continues to have access to num
, and num
is increasing the value by 1 in each execution. We can see it here:
The childFunction
in this case, is a closure where it has access to the num
variable of the parentFunction
, even though the parentFunction
had been called and closed.
A closure is created when we define a function, not when a function is executed.
Here's a great definition by w3schools:
A closure is a function having access to the parent scope, even after the parent function has closed.
Conclusion
Understanding closures is important to dive into more advanced concepts in front-end development. Also, it's a common topic in interviews. So, by grasping this concept, you'll level up your skills as a front-end developer.
Keep up the great work! :)