INTRO
I hope you people read my previous post on closure. If you still didn’t read it, please go throw it this link . Then you can understand this post very clearly. If you know the closure already, then no problem.
We have 3 different ways to achieve closure. Before understanding the Closure methods, you better to know Lexical Scoping, Function Currying and IIFE (Immediately Invoked Function Expression) concepts.
EXAMPLES
First Method
const outer=()=>{
let count = 0
const inner=(num)=>{
count += num
return count
}
return inner
}
const counter = outer()
console.log(counter(10))
console.log(counter(5))
console.log(counter(7))
In the above code, we have to mention outer function. Write inner function and return that inner function inside the outer function.
Note
: Inner function should return inside the outer function only
Second Method
const outer=()=>{
let count = 0
return inner=(num)=>{
count += num
return count
}
}
const counter = outer()
console.log(counter(10))
console.log(counter(5))
console.log(counter(7))
In the first method we are declaring and returning inner function different times. But in this method we are declaring and returning inner function at a time
Note
: First and Second Methods involves Function Currying and Lexical Scoping
Third Method
const outer=(()=>{
let count = 0
return (num)=>{
count += num
return count
}
})()
console.log(outer(10))
console.log(outer(5))
console.log(outer(7))
In this method no need to call closure function two times (calling outer function one time and calling inner function another time), we can call function as single function because outer function is already calling immediately after it declared
Note
: Third method involves IIFE and Lexical Scoping
For clear understanding the closure, it’s better to use the first and second methods. Otherwise using third method is best for code practice.
Top comments (0)