Closure, Currying and IIFE in JavaScript - DEV Community ? ?? ? PDF
Closure, Currying and IIFE in JavaScript - DEV Community ? ?? ? PDF
Ritik
2
JavaScript + FOLLOW
location
Ritik Apr 20 ・3 min read
India
Closure
Closure is a function that can remember all the things that are used in its
defination but are available outside its scope.
Lets see what this line means:
Join dev.to
function outerFunction(){
let i=2;
function innerFunction(){
console.log(i);
}
return innerFunction;
}
console.dir(outerFunction());
//[[Scopes]]:
//0: Closure (outerFunction) {i: 2}
You will see something like this when you run the sample code.
Lets break the code:
function outerFunction(){
let i=2;
function innerFunction(){
console.log(i);
}
return innerFunction;
}
Output is 2.
But outerFunction is already executed and its scope is vanished from stack.
So how does innerFunction()
get the value of "i" from outerFunction(). Does it Re-Run the
outerFunction()? NO!
function outerFunction(){
let i=2;
let j=3;
function innerFunction(){
console.log(i);
}
return innerFunction;
}
console.dir(outerFunction());
//[[Scopes]]:
//0: Closure (outerFunction) {i: 2}
Currrying
Currying is process of transforming a function which takes multiple
attributes into nested form of functions which takes
attribute one by one.
function multiply(x,y){
console.log(x*y)
}
multiply(5,4);
//20
Currying it:
function multiply(x){
return function(y){
console.log(x*y);
}
}
multiply(5)(4);
//20
function multiply(x){
return function(y){
console.log(x*y);
}
}
const multiplyby3 = multiply(3);
const multiplyby5 = multiply(5);
multiplyby3(2);
//6
multiplyby5(2);
//10
IIFE
IIFE stands for Immediately Invoked Function Expression. It is a design
pattern which helps in running a
function as soon as it is defined.
(function(){
//logic
})();
(function(){
console.log("Its an IIFE")
})();
//Its an IIFE
IIFE also provide other benefits, like it helps in making our variable and
methods private.
return{
createNewWorld: function(){
val = true;
},
destroyWorld: function(){
val=false;
},
result:function(){
val?console.log("New world is Created"):console.log("Your world needs to be recreated
}
})();
world.createNewWorld();
world.result();
//New world is Created
world.destroyWorld();
world.result();
//Your world needs to be recreated
In the above code sample variable "val" is a private member. We can not
access it directly.
The public methods under return function helps in accessing the private
member.
These public methods are the closures that share the same lexical
environment.
This is one of the application of closures.
The End
In this article we learn about Closures, Currying and IIFE. <3
This article is also available at ritikrana.in
Ritik + FOLLOW
PREVIEW SUBMIT
69 14 + FOLLOW
84 7 + FOLLOW
200 5