skip to Main Content
let foo = function(){
    console.log(1);
}
setTimeout (foo,1000);

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

I got the output as 1. But I need to know why because let can be reinitialized so its correct over here why didn’t I get the o/p as 2?

2

Answers


  1. The second variable is not declared when run this line setTimeout (foo,1000); you can check it by commenting the let foo = function(){ console.log(1); }

    Login or Signup to reply.
  2. the foo function is initially assigned to console.log(1), and then the setTimeout function is called on foo. This means that after 1 second, the foo function will execute and print 1 to the console. However, before the setTimeout function is executed, the foo function is reassigned to console.log(2), but this reassignment does not affect the setTimeout function that has already been called. Therefore, when the foo function is executed after the delay, it will print 1 instead of 2.

    let foo = function(){
        console.log(1);
    }
    setTimeout (foo,1000);
    
    foo = function(){
        console.log(2);
    }

    here the setTimeout function is called on a new function that calls foo. This means that after 1 second, the new function will execute and call foo, which will print 2 to the console. Unlike the first code, the reassignment of foo to console.log(2) occurs before the setTimeout function is executed. Therefore, when the foo function is called after the delay, it has already been reassigned to console.log(2) and will print 2 to the console.

    let foo = function(){
        console.log(1);
    }
    setTimeout(function(){
        foo()
    },1000);
    
    foo = function(){
        console.log(2);
    }

    Both methods involve using the setTimeout function to delay the execution of a function by a specified amount of time (1 sec in both cases). However, the difference lies in the timing of when the foo function is reassigned.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search