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

147
Vistas
Hoisting in Javascript example

In the following example, why does the second f() prints 2.

I was thinking it would print 3 since the function prints in the same context where it is called.

(function() {
  f();
  f = function() {
    console.log(2);
  }
}());

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

When function f() is hoisted, but f = function() is not hoisted, this results in following order:

// hoisted
function f()
{
  console.log(3);
}

(function () {
    f(); // uses definition with 3
    // overwrites f
    f = function()
    {
      console.log(2);
    }
}());

f(); // uses overwritten f with 2
about 4 years ago · Juan Pablo Isaza Denunciar

0

Here is the execution order.

  1. function f() hoisted

  2. IIFE executes and creates a global object called f

The second step overshadows the hoisted function due to its name and due to the fact that is being declared as a global variable

If you put var or let before the function expression Inside the IIFE and move the function call below the expression, the second call would have printed 3.

(function() {


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

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

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