0
function a(){
  function b(){
  }
}

In the above code of javascript, during the hoisting phase, will the function b be hoisted? Or just a will be hoisted because only function a is sitting lexically in the global context.

Will P.
  • 8,437
  • 3
  • 36
  • 45
W.Chen
  • 407
  • 1
  • 4
  • 6
  • Hoisting always happens *per scope*. `b` is hoisted, but only inside the function scope, whenever `a()` is called. – Bergi Dec 20 '16 at 19:33
  • which means `b` will not be hoisted if we don't call `a()`? – W.Chen Dec 21 '16 at 18:53
  • It means there will be no `b` if you don't call `a()`, and there will be as many `b`s as you call it multiple times. For `b`, you must only consider the scope `… { function b(){} } …` it lives in (which is the `a` function body) and nothing else. – Bergi Dec 21 '16 at 19:11

4 Answers4

4

b will be hosted to the top of the scope it appears in (the scope defined by the body of function a) during the hoisting phase when that function (a) is invoked.

b will not be exported to the global scope.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Function a will be hoisted to top of global scope (assuming this in the global scope) and function b will be hoisted to the top of the scope created by function a.

-1

Declarations are hoisted to the top of their containing scope, which for function b is function a.

Function b will be hoisted to the top of function a, but that is where it already is.

And, function a (based on your code) will be hoisted to the top of the Global scope.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
-1

In hoisting process all the declarations will move up below the parent function declaration.

Ex: function fun(){
    a = 10;
    var c = b();
    function b(){}
}

will become like

function fun(){
 var a;
 var c;
 function b(){};
 a = 10;
 c = b();
}
Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62