I have been working with the asynchronous function setTimeout in javascript. The following code gives different results when the parameter is passed in one setTimeout function and not in another. Can someone explain this?
Code 1:
console.log("Before");
getUserId(2);
console.log("After");
function getUserId(id){
setTimeout(() =>{
console.log(id);
}, 2000);
}
Output 1:
Before
After
2
and,
Code 2:
console.log("Before");
getUserId(2);
console.log("After");
function getUserId(id){
setTimeout((id) =>{
console.log(id);
}, 2000);
}
Output 2:
Before
After
undefined
In the second example, you are redefining scope for the variable id
in the callback passed to setTimeout()
. In other words this is the same as:
function getUserId(id){
setTimeout((some_other_id) => {
console.log(some_other_id);
// some_other_id is undefined
}, 2000);
}
Understanding the scope of id
will explain / fix your problem.