Closure
in J avas c ri pt
Closures are a very important feature in
JavaScript. They're fundamental to how
the language works and are used all the
time, even when you don’t realize it.
Here's a brief
explanation: page 01
@diveintodev_
Definition
A closure is created when a function
accesses a variable that is defined in its
outer scope, even after that outer
function has finished executing.
In other words Inner function can
access outer function variable
page 02
@diveintodev_
EXAMPLE - 1
page 03
@diveintodev_
What’s happening here?
outerFunction returns innerFunction.
counter is a variable in outerFunction's
scope
Even after outerFunction is done
executing, innerFunction keeps a reference
to counter.
Every time myClosure() is called, it updates
and logs the same counter. page 04
@diveintodev_
EXAMPLE - 2
Here, count is private. It can only be
accessed via increment and decrement.
page 05
@diveintodev_
Follow for more
Aditya Gaurav
LinkedIn- https://www.linkedin.com/in/adityagaurav-
Instagram - diveintodev_
like share save