We have been declaring functions that are manually invoked but what about a function that is self invoked? This is where IIFEs come in handy.
Supposing I have a function expression that returns the sum of 10 and 10
A function expression is a function that is assigned to a variable.
let sum = function (a, b){
return(a+b);
}
This is how I will invoke it
sum(10, 10);
Here's my result
So how do I change it to an IIFE?
To change it to an IIFE, you just need to enclose both the function, and the necessary arguments for invoking it in a parenthesis.
Look at the code below for implementation
let sum = (function (a,b){
return(a+b);
})(10,10);
You can see that I have enclosed the function in a parenthesis, and the required arguments right beside it, in a parenthesis too.
When I paste this code in my console, it gets invoked immediately because we directly provided the arguments needed for its invocation right after the function expression.
With this function invoked immediately, our result is already saved to the variable sum.
So all I have to do is to print out the value
That's how you declare an IIFE in JavaScript.