INTRO
I hope you people read my previous post on closure. 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'd better 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 the outer function. Write an 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 functions different times. But in this method, we are declaring and returning an inner function at a time
NOTE: The first and second methods involve 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, there is no need to call the closure function two times (calling the outer function once and calling the inner function another time); we can call the function as a single function because the outer function is already called immediately after it is declared
NOTE: The third method involves IIFE and lexical scoping.
For a clear understanding of the closure, it’s better to use the first and second methods. Otherwise, using the third method is best for code practice.