Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda