🖥️ Developer Resources
JAVASCRIPT
CLOSURE SAVE IT NOW 🥰
@ayush.codes
Ayush Gupta Swipe-->
Hey Everyone 👋
Closure is one of the important concepts in
JavaScript. It is a widely discussed and still
confused concept. Let’s understand what
the closure is.
Before you learn about closures, you need
to understand two concepts:
Nested Function
Returning a function
Ayush Gupta @ayush.codes
Nested Function
In JavaScript, a function can also contain
another function. This is called a nested
function.
Ayush Gupta @ayush.codes
Returning a Function
In JavaScript, you can also return a
function within a function.
Ayush Gupta @ayush.codes
JavaScript Closure
Closure means that an inner function
always has access to the variable of its
outer function, even after the outer
function has returned.
Ayush Gupta @ayush.codes
How it works:
1. In the above example, when OuterFunction()
function is called, it returns the function
definition of InnerFunction.
2. Here, innerFunc is a reference to the
InnerFunction() function, because of our first
point.
3. When innerFunc() is called, it still has access to
the OuterFunction() function.
4. When we run console.log(innerFunc), it returns
the function definition.
5. When we run console.log(innerFunc()), it returns
InnerFunction() value, because of our Second
point.
Ayush Gupta @ayush.codes
Let’s have a look at another example.
Ayush Gupta @ayush.codes
How it works:
the calculate() function takes a single
argument x and returns the function
definition of the multiply() function.
The multiply() function takes a single
argument y and returns x * y.
Both multiply 3 and multiply 4 are closures.
The calculate() function is called passing a
parameter x.
When multiply 3(6) and multiply 4(2) are
called, the multiply() function has access to
the passed x argument of the outer
calculate() function.
Ayush Gupta @ayush.codes
Was it
helpful
follow for more!
Like
Comment
Share
@ayush.codes
Ayush Gupta
Tech Simiplifed