In simple words,
Now let me show you some magic!
You will definitely guess that the getName() will call the function getName() and then console.log will print the value of x on console.
But wait for the magic,
What has changed here?
We are trying to access getName() even before we have initialized it, we are trying to x even before we have put some value in it.
In most of the programming languages this would result out to be an error since you can’t access variables before you’ve initialized it.
As we see, “Hey hi, this is Janhvi” is printed. It means, getName() is somehow able to access the getName() function and invoke the function directly. But in case of console.log we get a special value named “undefined”.
Okay so lets play with it more!
Any guesses about the output now?
Now it says, x is not defined.
Earlier it was undefined!
Confused?? I’m here to help you out.
Are you thinking, is the undefined and not defined the same thing?
Ans: No, it’s not!!
Heading to one more interesting thing,
Let’s try to console log our getName() function.
See, we aren’t invoking the function, we are just trying to print the function on the console. So, it actually prints the function on the console.
But what if we try to access the function even before initializing it?
But it wasn’t the same in case of x,
In case of x, it was giving us undefined but in case of functions, it is print the function.
Even before the start of execution of the first line code, the memory is allocated to each and every variable and function. And it stores a special keyword “undefined” for these variables and keeps an actual copy of the function even before we are trying to run the code.
But, if variables are declared and initialized nowhere in the memory, then it gives ReferenceError: x is not defined.
Some part of twist is still left,
Let’s try invoking the getName() as an arrow function.
It throws error!
Because if we are using function as arrow function then it behaves as just another variable and assigns the value of undefined to it if we check in the execution context.
There’s one more way to declare a function,
It also behaves as a variable and allocated a memory with a placeholder undefined.
Output: 5 7
Output: x is 5 and y is undefined
Link of official documentation: Hoisting – MDN Web Docs Glossary: Definitions of Web-related terms | MDN (mozilla.org)
Shocked?? Yes, it’s empty!
Let’s keep it for another article. Till then, for more updates on this stay tuned and don’t forget to follow BePractical!