Function Expression & IIFE
What are JavaScript functions?
Functions are essential building blocks in JavaScript, they are packed with logic for performing tasks. A function can be likened to a procedure that performs a task or calculates a value. However, for this procedure to be considered as a function, it needs to take some input and return an output.
Function Expression
Function Expressions are two types:
In the above code a lot of things will happen. Let's talk about that-
In The above code we can see there are a lot of ways to implement a function. In JavaScript everyone has a specific meaning so lets see-
Whenever your function declaration starts with a keyword function(in line no 1 fig) that is called function declaration. If you see in line no. 4(in fig) we are defining a function but the first expression is not a keyword function it is let in that case it is called a function expression . In line no 10 & 14 first valid piece of code is parenthesis here it is not a keyword function so here also it is a function expression.
领英推荐
Let's Talk About IIFE
IIFE stands for Immediately Invoked Function Expression. It means you wrote a function expression and you immediately call it, that is IIFE.
Use Case of IIFE
Use Case of Named Function
The main use Case of the named function is Readability. It increases the readability of the code if you have a very huge code base and you just passed your function expression without the name making it anonymous and do that nobody stops you but the readability of the code decreases.This is the first point which is in favor of named function expression. Another use case, in recursion if we use anonymous function expression and we perform recursion on it then how do you do recursion? That's problematic so for recursive cases the named function is helpful.