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?
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
The second variable is not declared when run this line
setTimeout (foo,1000);
you can check it by commenting thelet foo = function(){ console.log(1); }
the
foo
function is initially assigned toconsole.log(1)
, and then the setTimeout function is called on foo. This means that after 1 second, thefoo
function will execute and print 1 to the console. However, before the setTimeout function is executed, thefoo
function is reassigned toconsole.log(2)
, but this reassignment does not affect the setTimeout function that has already been called. Therefore, when thefoo
function is executed after the delay, it will print 1 instead of 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 callfoo
, which will print 2 to the console. Unlike the first code, the reassignment offoo
to console.log(2) occurs before the setTimeout function is executed. Therefore, when thefoo
function is called after the delay, it has already been reassigned toconsole.log(2)
and will print 2 to the console.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.