2

Here is my javascript code :

    console.log(a);
    c();
    b();            
    var a = 'Hello World';
    var b = function(){
        console.log("B is called");
    }
    function c(){
        console.log("C is called");
    }

Now here is output :

undefined
hoisting.html:12 C is called
hoisting.html:6 Uncaught TypeError: b is not a function

My question is regarding why c() and b() behaving differently. And b should throw error something like b is not defined.

georg
  • 211,518
  • 52
  • 313
  • 390
Aniruddha
  • 3,513
  • 6
  • 27
  • 38
  • Possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Thilo Feb 07 '16 at 12:26

4 Answers4

2

A Function Declaration will be hoisted along with its body.

A Function Expression not, only the var statement will be hoisted.


This is how your code "looks" like to the interpreter after compiletime - before runtime:

 var c = function c(){
      console.log("C is called");
 }

 var a = undefined
 var b = undefined

 console.log(a); // undefined at this point
 c(); // can be called since it has been hoisted completely
 b(); // undefined at this point (error)

 a = 'Hello World';
 b = function(){
     console.log("B is called");
 }

KISSJavaScript

Community
  • 1
  • 1
soundyogi
  • 369
  • 3
  • 15
  • Thanks. I added console.log(b) & console.log(c) statement to verify your answer. And you are spot-on. Thanks – Aniruddha Feb 07 '16 at 12:42
1

Function Expression:

  var b = function(){
        console.log("B is called");
    }

Function Declaration:

function c(){
    console.log("C is called");
}

Function Expressions loads only when the interpreter reaches that line of code.On the other side the function Declaration, it'll always work. Because no code can be called until all declarations are loaded.

Read more about Function Declaration and Function Expression

Yehia Awad
  • 2,898
  • 1
  • 20
  • 31
0

At the time you are calling b is not defined yet. Your b is a variable which contains function, and the time you are accessing b it has not been defined yet.

xxxmatko
  • 4,017
  • 2
  • 17
  • 24
0

Because declare a function with Function Expression create an anonymous function unless you explicitly provide a name :

var b = function() {}   // anonymous function 

and differently when you declare a function with Function Declaration, you set a name :

function c() {}   // c function 
cicciosgamino
  • 871
  • 3
  • 10
  • 29