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

Jeffrey Ram
  • 1,132
  • 1
  • 10
  • 16
Ranganath MD
  • 128
  • 2
  • 9
  • 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'. – Nicholas Tower Aug 28 '22 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 https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/ – Shiny Aug 28 '22 at 14:48

1 Answers1

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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175