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.
Can someone please explain why it is not reassigning the name to 'xyz'?It does reassign it, but that code happens after everything else, so it's not very useful. You create name = 'abc', then you set a timeout, then you return 'abc', then you log 'abc'. Later on, the timeout goes off and you assign 'xyz'.