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
let testFunction = function() {
console.log('Hello')
}();
let testFunction = function() {
console.log('Hello')
}();
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
testFunction
testFunction
i get undefined
cosole.log(testFunction())
cosole.log(testFunction())
thanks in advance for your help
3 Replies
ChooKing
ChooKing10mo ago
The first version is a Immediately Invoked Function Exression (IIFE). The console log should be undefined, because that function isn't returning anything.
Joao
Joao10mo ago
Just to clarify the above, the following is an Immediately Invoked Function Expression (IIFE):
(function(){
console.log('hello');
})();
(function(){
console.log('hello');
})();
It's a function definition followed by the invocation of that function, so it resolves immediately, hence the name. Now to your example:
let testFunction = function() {
console.log('Hello')
}();
let testFunction = function() {
console.log('Hello')
}();
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.
dellannie
dellannie10mo ago
Thank you. This makes a lot of sense now compare to what I was trying to figure out