question about assigning a function to a variable
I'm testing and trying out some new things I recently learn about functions and I come across something like this
now this works and shows the hello on the console. However I decide to take away the at the end and I no longer see the hello on the console.
Then I try this to see if the hello would show up but instead I get two things Hello and undefined. I have an idea of whats going on and I think the in the first statement automatically invoke without being called i think but i'm not sure and I can anybody help me understand why when I console log i get undefined
thanks in advance for your help
3 Replies
The first version is a Immediately Invoked Function Exression (IIFE). The console log should be undefined, because that function isn't returning anything.
Just to clarify the above, the following is an Immediately Invoked Function Expression (IIFE):
It's a function definition followed by the invocation of that function, so it resolves immediately, hence the name. Now to your example:
To explain why the following shows undefined:
console.log(testFunction)
you need to understand one very important thing about functions. All functions return something, but if you don't specify what that something is then it defaults to undefined
.
So in in this case you are defining a function, that logs 'Hello' to the console and returns undefined
, and calling it immediately. The return value of that function call is assigned to the variable testFunction
.Thank you. This makes a lot of sense now compare to what I was trying to figure out