Shivam Muttoo
Shivam Muttoo

Reputation: 89

What happens during hoisting?

I was going through the hoisting concept of javascript.

    var a = 2;
    function a(){};
    typeof a 
    // "number"

    var a ;
    function a(){};
    typeof a 
    // "function"

My question is, why first code has typeof number instead of funtion which can be seen in second part of the code?

Upvotes: 1

Views: 62

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36584

function declarations hoists first than normal variable initialization.
The variables declared with var shows hoisting. The declaration of a goes to top of scope but its assigned the value 2 on the line where its written.

The function declaration i.e function a(){}; declared the value and also assigns the value to function at top of scope. So whats happening in first example is

var a = function(){};
a = 2;
console.log(typeof a) 

In the second example the variable is initialized to a function. But var a doesnot change a from function to undefined

var a = function(){};
a; //this doesnot change a
console.log(typeof a);

Upvotes: 2

brk
brk

Reputation: 50326

If you break the first code it looks like this. In js, function declarations hoist the function definitions.

To show the function declarations hoist the function definitions you can call function a() before declaration

var a; // a is undefined
a();

function a() {
  console.log('function a');
}; // function is also hoisted
a = 2; // a is assigned a value
console.log(typeof a)

Upvotes: 2

Related Questions