Sunday, July 3, 2022

IIFE(Immediately Invoked Function Expression) & Arrow function

 Immediately Invoked Function Expression(IIFE) is an anonymous function which gets invoked immediately. It is anonymous because it does not have a function name. The nature of this kind of function are self invoking. 



Here we can see that we have declared a function without a name. Inside a block function it has defined a variable with number 30 locally which is not defined outside the block. Therefore, we can see lexical behavior here also.

Below are some related questions to IIFE.

1.What is Name Collision?

2.Normal Function vs IIFE?

  • At the time we create normal function we can have name collision but incase of IIFE we don't face this problem.

3.What is the use of IIFE?

  • To not have a name collision is the use of IIFE. 


Arrow Function:
Arrow function allows us to shorten the syntax of function as compared to normal function.






Saturday, July 2, 2022

What is Closure in JavaScript?

 Closure in JavaScript are the function inside a function that makes a function stately. Moreover, closure in JavaScript is the combination of function bundled together with references with its surrounding which is lexical environment. In other words, closure allows us to give the excess to outer function from inner function.


What is the need of closure?

The use of closure is to create self content functions, self content code, self content module. And, anything we have self content, then we have self content state. And when we are having self content state then we are avoiding global variables. 




From above example we can see that we have a simple() function which has initialized x as 0. Right after that x is incremented to 1. When the function is invoked, x will be shown as 0 at first and 1 later and at the end memory will be cleared. This means, next time again we invoke simple fun(), same values will be shown. This states that the function is stateless. 

On the other hand, there is a closures() function that has got another inner function init(). Variable x is initialized to 0 at first right after that init() function is incrementing the x variable defined in closures() function. We also have a reference variable for closures() function. Here in case of closure function we can have a reference that says don't let go the memory variables. So this makes function stately. 
Therefore, until and unless we end our reference variable in the use, we are able to use the memory memory variables. Here in the example every time we use reference variable we get the incrementation of the varaible.  
   

IIFE(Immediately Invoked Function Expression) & Arrow function

 Immediately Invoked Function Expression(IIFE) is an anonymous function which gets invoked immediately. It is anonymous because it does not ...