2
function a(){ 
   console.log(typeof b); // function
   function b() {
     var c = 52; 
     console.log(c);
   } 
   var b = 88;  
   console.log(typeof b); // number 
}

Could anyone answer, how javaScript compiles or handles this particular case ? I know javaScript gives preference to function declaration when it comes to hoisting. But how a same identifier b holds two different values under same block or in same lexical scoping?

Someone could say like, okay, I'm going to use b as a function before it's declaration and as number after assigning it a number.

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Sachin Bhandari
  • 524
  • 4
  • 19
  • 2
    Possible duplicate of [Order of hoisting in JavaScript](https://stackoverflow.com/questions/28246589/order-of-hoisting-in-javascript) and [javascript hoisting for global variable and function](https://stackoverflow.com/questions/51255345) and [Function declarations precedence/overwriting variable declarations? Hoisting? Why?](https://stackoverflow.com/questions/46015380) – adiga May 28 '19 at 19:01

3 Answers3

3

You can understand as such there are two phase of code execution

  1. Creation phase
  2. Execution phase

Creation phase:- During creation phase function is hoisted at top as it is, while the variable are hoisted but there is no value assigned to it ( or you can say it's value is undefined )

Execution phase:- During execution context it assigns value to variable when it reaches line where assignment is happening

so in your code during creation phase function b is hoisted, compiler will read it like this

function a(){ 
   function b(){
     var c = 52; 
     console.log(c);
   } 
   console.log(typeof b); // function
   b = 88;  
   console.log(typeof b); // number 
}

so when you reach to the line

b = 88

it assign a new value to variable b which is of type number

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

As far as I know, those aren't 2 different references.

Internally, function b(){/*Code Here*/} is executed as var b = function(){/*Code Here*/} Hence, the first typeof(b) returns function.

And when var b = 88; executes, this basically assigns 88 to the already existing reference of b. Hence, the second typeof(b) returns number.

Runtime image for reference: enter image description here

Arjun Mudhaliyar
  • 156
  • 3
  • 10
0

In this case, the hoisting happens as follows:

  1. declare var b, without initialization
  2. declare function b, which overrides the var declaration
  3. assign value 88 to variable b

So the function actually gets converted to the "logical equivalent" of:

function a(){ 
   var b; // hoisted
   b = function b(){ // hoisted
     var c = 52; 
     console.log(c);
   } 
   console.log(typeof b); // function
   b = 88;  
   console.log(typeof b); // number 
}

Note: Only declarations are hoisted, not initializations

Gaurav
  • 562
  • 3
  • 12