Why do some lines of code execute before others in Javascript? None of it is asychronous

403 views Asked by At

When I do:

<!DOCTYPE html>
<html><head><title></title></head>
<body>
    <div id="root"></div>
    <script>
        let a = document.getElementById('root');
        console.log(a);
        a.append('cat');
        console.log(a);
    </script>
</body></html>

I expect the console to be:

<div id="root"></div>
<div id="root">cat</div>

But I get:

<div id="root">cat</div>
<div id="root">cat</div>

Its like the .append('cat') command runs before the first console.log() command. How is this? I thought programming code was always executed sequentially. Where can I learn which code executes sequentially and which ones don't in Javascript?

This might be a problem if I'm trying to debug more complex code later.

1

There are 1 answers

12
Daniel On

I am using firefox and I am getting the expected output of (in stackOverflow). However innerText and innerHTML are logging with the same "unexpected behavior" that you are experiencing when run as a .html document.

<div id="root"></div>
<div id="root">cat</div>

It appears that the "problem" is due to the console logs of html nodes from the DOM referencing the DOM in real time. Therefore if you change the node, the console log will UPDATE to show that change.
You should therefore not console log nodes if time specific console logs of old nodes is important information to you. Instead us innerHTML to get the information as an immutable string that will not update along with the nodes.

<!DOCTYPE html>
<html><head><title></title></head>
<body>
    <div id="root"></div>
    <script>
        let a = document.getElementById('root');
        console.log(a);
        a.append('cat');
        console.log(a);
    </script>
</body></html>