2

I have this code with function declaration and addittional block statement who's make new lexical environment:

console.log("1:"+foo);
{
  console.log("2:"+foo);
  function foo(){ console.log("checked"); }
  console.log("3:"+foo);
}
console.log("4:"+foo);

Why first log output undefined? Yes, the function is hoisted. But it's unclear why inside the block statement we get this function before the declaration and after the declaration, but outside the block before the declaration we get undefined. I would like to get an explanation from the point of view of the specification.

MaximPro
  • 563
  • 8
  • 21
  • 4
    Related: https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6 – CertainPerformance May 06 '18 at 05:00
  • 1
    function is hoisted inside the block – thaveethu gce May 06 '18 at 05:21
  • Because you are using sloppy mode. – Bergi May 06 '18 at 10:15
  • @Bergi Does the specification not describe hoisting? – MaximPro May 06 '18 at 19:42
  • @MaximPro It describes very well what happens, but it doesn't use the term "hoisting". Have you read my answer that CertainPerformance linked, and the relevant spec sections? – Bergi May 06 '18 at 19:47
  • @Bergi Partially. Stop but where are the references to the specification so that you can track what happens and how, and you answer literally on an honest word. – MaximPro May 06 '18 at 19:57
  • @MaximPro There's no spec reference in my answer, but in the question - mainly Annex B describes what happens in this case, and the annex references all the relevant parts of the spec. – Bergi May 06 '18 at 20:00
  • 2
    This is the part in the spec that Bergi refers to: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-block-level-function-declarations-web-legacy-compatibility-semantics – Felix Kling May 07 '18 at 18:11

0 Answers0