The time has come to meet seen almost everywhere, the very popular IIFEs.
Immediately Invoked Function Expressions
What is IIFE really?
Let's start with the fact that we already know what a Function in programming is , and more precisely a Function Expression.
In addition, we know what Invoking means, and if you have read previous posts and you have survived up to this point, it means that you are doing well with English, so you know does Immediately mean.
So Immediately Invoked Function Expression is really just that what you read word by word. After the example below, I think that all doubts will disappear. Let's get started.
At the start, a reminder of what we know about Function Statement.
In the example above, we have the function hello, which takes one parameter: name.
Thanks to it, in the console we get:
Everything works as it should.
Then we have Function Expression.
Of course, everything works as it should too.
Now we will change a bit our Function Expression.
As you can see a lot has not changed. Thanks to it, we created the first Immediately Invoked Function Expression.
By passing "Tom" this way, we do not have to invoke the function later, as we did with Function Expression.
Let's also look at two examples below.
As you can see in both cases, our functions this time return something.
What will we get if check what value is stored in the helloFunction and helloF variables ?
By using IIFE, the helloFunction variable stores the value immediately.
However, if you would want to pass to both functions, the argument "Tom" in the following way.
And then if we check what is stored in the variables, we will get similar to what we received last time.
Finally, I would like to show one more form of Immediately Invoked Function Expression. However, before we take a look at it, I would like to show the a bit strange example.
We see something that looks almost like Function Statement, and almost like Function Expression.
For it to be the second one, there has to be of course a variable in which we would store what the function returns.
To be the first one, the name of the function is missing and it is clearly visible when we run the console.
This is of course due to the fact that Syntax Parser knows that after the function, if the line of code starts from it, there should be the name of the function, as it is in all Function Statements.
But if we include the whole function in the brackets: (), we will trick the engine. Now it will be expecting the Function Expression.
The above example will no longer cause any errors. In addition, if we want to pass to the name parameter for example "Tom" we will be able to do it this way.
I suggest, of course, to play with them to better understand that it is not really complicated, and the name of the concept describes well what we are dealing with.
We will talk about Closures.