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?