I written below script and executed in scratch pad.
baz();
var baz = function(){
console.log("Hello World");
}
When I try to execute above script, I got below kind of exception. I know, this expression comes because, hoisting is not valid for function expressions.
/*
Exception: TypeError: baz is not a function
@Scratchpad/1:1:1
*/
Now, I replaced the function name 'baz' with 'say_hello', and re run the application, it is working fine with no exception. Is there any reason for this behaviour?
say_hello();
var say_hello = function(){
console.log("Hello World");
}
This is the one which is really working fine with no exception
The reason is:
If a variable is declared and initialized after using it, the value will be undefined. For example:
If you declare the variable after it is used, but initialize it beforehand, it will return the value:
For more information:Only Declarations Are Hoisted