简体   繁体   中英

strange behaviour in function Hoisting

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"); } 

 say_hello(); function say_hello(){ console.log("Hello World"); } 

This is the one which is really working fine with no exception

The reason is:

JavaScript only hoists declarations (variable and function declarations), not initializations

If a variable is declared and initialized after using it, the value will be undefined. For example:

console.log(num); // Returns undefined 
var num;
num = 6;

If you declare the variable after it is used, but initialize it beforehand, it will return the value:

num = 6;
console.log(num); // returns 6
var num;

For more information: Only Declarations Are Hoisted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM