3

This is the example:

function b() {
  console.log(f); 

  {
    function f() {}
  }
}

b()

I thought it would become:

function b() {
  // hoist to function scope
  function f() {}
  console.log(f); // should output function f
}

or

function b() {
  console.log(f); // should output reference error
  {
     // just hoist to block scope like this
     function f() {}
  }
}

but it outputs undefined, like var hoisting. why?

adiga
  • 34,372
  • 9
  • 61
  • 83
  • 1
    Function declarations haven't been allowed before ES2015, but browsers still supported it, but every browser did this differently. ES2015 describes this behavior in an appendix: https://www.ecma-international.org/ecma-262/6.0/#sec-block-level-function-declarations-web-legacy-compatibility-semantics . Depending on the context (non-strcit vs strict), the function declaration is basically evaluated as a variable declaration that is assigned a function expression. In strict mode this code throws an error. – Felix Kling Feb 21 '19 at 05:23

2 Answers2

0

{} creates block scope so

JS engine will interpret your code something like this

function b() {
  console.log(f);
  {
    var f = function f() {};
  }
}

b();

So because of block scoping value of f is not available out of block. and since it is defined as var it is hoisted to parent's scope ( function b's scope ) and turns out to be undefined

If you remove {} .

function b() {
  console.log(f); 
  function f() {}
}

b()
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 3
    Should be `var f = ...` in the first example. *"it is hoisted to global scope"* No, it's not global it's hoisted inside the function's (`b`) scope. – Felix Kling Feb 21 '19 at 05:24
  • @FelixKling yeah i just forgot to remove `_`'s after copying from babel repl. updated thanks for your inputs :) – Code Maniac Feb 21 '19 at 05:28
  • Remove ```{}``` inside ```function b()```. This is because console statement is out of the scope of the declaration of function f() – HOTAM SINGH Feb 21 '19 at 07:05
0

It's due to Hoisting. The function f() {} is inside a block, therefore console.log(f) cannot access the function f() {}, that is out of the scope. However, if you keep the console.log(f) inside the block {}. Hoisting should work.

TheParam
  • 10,113
  • 4
  • 40
  • 51
Dipesh Lohani
  • 306
  • 3
  • 11
  • 2
    The question is "how does hoisting work here" and you are basically saying "it's because of hoisting". It's not really an explanation of what's going on. – Felix Kling Feb 21 '19 at 05:26