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