Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

57
Vistas
Why does JS function show in block scope if it is hoisted in global scope?

I was playing around with JS scopes to get a better understanding of the concept. Doing that I wrote the following script:

{
  let a;
  function x() {
    let p;
    var q;
  }
}

x();

Surprisingly, when debugging in the Chrome dev console, I realized that if I stop the script at line 2 or let a, I can see the block scope having both variable a and function x as visible in screenshot 1.

Also, on logging window.x outputs undefined However, as soon as I jump on to the next breakpoint which is line 4 or let p, the block scope is no longer there and a local scope is created. Now, on logging window.x outputs the function definition.

Now as I understand, since I am able to call x() from the global scope means that the function declaration is available in the global scope. Then why isn't the function binding available before the creation of function's execution context (if it is hoisted to global scope)? And why does writing x() at the top of the block output TypeError: x is not a function?

screenshot 1

Note: I am not writing functions like this anywhere, i just wrote this script to test my understanding of scopes. Apologies if this is a wrong way of writing functions.

EDIT per comments:

Chrome and FF show undefined while Safari shows function definition.

console.log(x); // logs undefined
{
  let a;
  function x() {
    let p;
    var q;
  }
}

x();

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos