strange behaviour in function Hoisting

55 views Asked by At

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

1

There are 1 answers

0
Tu Nguyen On

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