0

JS sequentially executes code line-by-line. Check out this below example:

function tellMeWhatsPassed(thing){
   console.log(thing)
}

function createThing(){
   const div = {}
   div.innerHTML = 'original'
   tellMeWhatsPassed(div)
   div.innerHTML = 'updated'
   tellMeWhatsPassed(div)
}

createThing()

// {innerHTML: 'original'}
// {innerHTML: 'updated'}

EXPLANATION OF ORDER OF HOW CODE EXECUTES

To quickly walk through - JS takes the identifier tellMeWhatsPassed and bundles the code for further execution and moves to the next line.

It then does the same for createThing.

Once it reaches the call for createThing we begin executing that function. Inside of that execution context we create an object in local memory where we define an empty object and assign a key value pair: innerHTML and 'original', respectively.

We then call tellMeWhatsPassed with the object, div which is: {innerHTML: 'original'} , as the argument. tellMeWhatsPassed simply console logs the passed argument.

Then we return to createThing to continue execution and mutate the key which results in this object {innerHTML: 'updated'}

Then when tellMeWhatsPassed is called and given the above argument it simply console logs it.



Here we are going to update createThing to create a div HTML element instead of an object. The Thread of execution gets wonky.

function tellMeWhatsPassed(thing){
   console.log(thing)
}

function createThing(){
   const div = document.createElement('div')
   div.innerHTML = 'original'
   tellMeWhatsPassed(div)
   div.innerHTML = 'updated'
   tellMeWhatsPassed(div)
}

createThing()

// <div> updated </div>
// <div> updated </div>

I can't wrap my head around what's causing this behavior. What breaks the sequential execution?

OReilly
  • 83
  • 4
  • 6
    It is sequential execution. But the DOM isn't rendered immediately when you change `innerHTML`, that only happens when the code returns to the main event loop. This allows JS to make many changes without the user seeing all the intermediate steps. – Barmar Feb 17 '23 at 21:46
  • 2
    The sequential DOM updates (which aren't handled by JavaScript; that's the DOM API) are going to be completed one after the other in a very small amount of time. By the time the console code gets around to writing to the console, the second update is all it can see. – Pointy Feb 17 '23 at 21:47
  • 2
    If you change your `console.log` to `console.log(thing.innerHTML);` (i.e. a primitive value, not a reference to the DOM element, which gets updated) you'll see the expected result – blex Feb 17 '23 at 21:49

0 Answers0