A Beginner's Guide to JavaScript Closures

To understand in Closure very first step is to understand function

1.There are mainly four types of function in javascript.
eg:
1.Normal function
function f(c,d){
const multiply= c*d;
return multiply
}
console.log(f(4,5)); //20

2.Anonymous function
let f = function(a,b){
const multiply = a*b;
return multiply
}
console.log(f(5,4)); //20

3.ImmediateInvoke
let f = function(a,b){
const multiply = a*b;
return multiply
}(2,6)
console.log(f(2,4)); //8

4.ArrowFunction
let f=(a,b) =>{
const multiply = a*b;
return multiply;
}
console.log(f(4,6)) // 24

2. Function Inside Function
function fun(){
function multiply(a,b){ // Or return function(a,b){
const result= a*b; // const result= a*b;
return result; // return result;
} }
return multiply;
}
var multiFun = fun();
console.log(multiFun(2,3)); //6

3.Closures
var createCounter = function(n) {
let count = n;
return function() {
return count++;
};
};
const counter = createCounter(10)
console.log(counter); // it will return the function() and initialize the count variable with n counter() // 10

counter() // 10
counter() // 11 →This counter() call the inner function() but inside the block count variable is not present so it will search for outer function and i.e, lexical env and perform the operation in that and this is called closure
counter() // 12