Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
Hoisting vs Scope Chain

How come, in the first block of code, I get "Hello", but in the second block of code, I get undefined, then "bye"?

For the first block of code, I get that it is going up the scope chain to get the hoisted variable "Hello", which I get the expected result.

    var greet = "Hello";

    var sayHi = () => {
        console.log(greet);
    }

    sayHi();

However, I'm struggling to understand how come, if I declare the variable greet after the first instance of console.log, I get undefined first? Shouldn't the JS engine go up the scope chain to find "Hello" first?

        var greet = "Hello";

    var sayHi = () => {
        console.log(greet);

        var greet = "Bye"; 
        console.log(greet);
    }

    sayHi();
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

There is a difference between declaration and initialization. Declaration creates the variable, initialization assigns it its initial value. The statement var greet = "Bye"; contains both things, but only the declaration is hoisted.

about 4 years ago · Juan Pablo Isaza Denunciar

0

In the second block after hoisting, it is executed as below. That's why you see undefined and then Bye.

var greet = "Hello";

    var sayHi = () => {
        var greet;
        console.log(greet);

        greet = "Bye"; 
        console.log(greet);
    }

    sayHi();

Within the function, it sees the greet variable is defined in its scope. It won't look up in the scope chain as you expect.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda