0

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'?

2
  • 2
    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'. Commented Aug 28, 2022 at 14:45
  • 1
    I think the problem here is likely not understanding that Javascript is mostly synchronous, and non-blocking, so the code execution doesn't wait for that setTimeout to resolve, and instead continues to the return - This is what async / await is used for -- There should be lots of resources to explain this concept, but here's the first I found to point in the right direction freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript Commented Aug 28, 2022 at 14:48

1 Answer 1

0

In order to understand this behavior, you need to understand how the event loop works:

enter image description here

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.