Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Behaviour of javascript interpreter

my html file :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    <li>Grapes</li>
</ul>
<script src="script.js"></script>
</body>
</html>

My js file:

const ul = document.querySelector("ul");
const firstListItem = ul.firstElementChild;
console.log(firstListItem);
const button = document.createElement("button");
button.textContent = "I have been added later";
firstListItem.appendChild(button);

So, what I have learnt is that javascript interpreter goes line by line and executes code. So when i log out firstListItem, it should log out just

<li>Grapes</li>

Why does it log out

<li>Grapes<button>I have been added later</li>

because, I added button later in my js code, shouldn't it just log out Grapes?

1 Answer

it is, it is just happening so fast that by the time the console updates the button has been added. i added a timeout of 100 ms before the button is added and it logs what you expected. if 100 isn't enough on your computer increase it.

const ul = document.querySelector("ul");
const firstListItem = ul.firstElementChild;
console.log(firstListItem);
const button = document.createElement("button");
button.textContent = "I have been added later";
window.setTimeout(() => 
firstListItem.appendChild(button),100);

okay, I tried that and it works but if its just a matter of giving time to console then why not add a for loop :

const ul = document.querySelector("ul");
const firstListItem = ul.firstElementChild;
console.log(firstListItem);
for(let i=0; i < 10000; i++){
    console.log("A");
}
const button = document.createElement("button");
button.textContent = "I have been added later";
firstListItem.appendChild(button);

This should log out my desired output, but it still logs out the button in li element, moreover, before "A" is logged out 10000 times firstListItem does not log out, there is a space for it in the console but nothing there, as soon as "A" has been logged out 10000 times, that empty space contains the the li element containing button. Why is that happening?