Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!