function delay2sec(){
let name = "abc"
setTimeout(function () {
name = "xyz"
}, 0)
return name
}
console.log(delay2sec())
The output is abc.
Can someone explain why it is not reassigning the name to 'xyz'?
function delay2sec(){
let name = "abc"
setTimeout(function () {
name = "xyz"
}, 0)
return name
}
console.log(delay2sec())
The output is abc.
Can someone explain why it is not reassigning the name to 'xyz'?
In order to understand this behavior, you need to understand how the event loop works:
Your setTimeout
adds an event to the event loop, which will be executed after the current function. Your return
statement is evaluated before the current function ends, so the return
evaluates the value before the change.