In this exercise, you’ll learn how programs run in order, how functions and events change that flow, and how API calls return data asynchronously. By the end, you’ll be able to predict program behavior, attach event listeners, and understand how callbacks work with real-world APIs.
Look at this code:
console.log("A");
console.log("B");
console.log("C");
Question: What will be printed on the screen? Write the exact order.
Modify the code to add a fourth console.log("D"); at the end. Run it.
Answer: Write the new order of output.
Predict what this code will do:
function setBackground() {
document.body.style.backgroundColor = "blue";
}
setBackground();
Question: What color will the background be after the function runs?
Change "blue" to another color of your choice. Test again.
Answer: Write the new background color.
Add a button to your HTML:
<button id="esButton">Click Me</button>
Attach an event listener:
const esButton = document.getElementById("esButton");
esButton.addEventListener("click", () => {
document.body.style.backgroundColor = "green";
});
Question: What color will the background be after clicking the button?
Experiment: Change "green" to another color. Test again.
Answer: Write what happened.
Look at this fetch request:
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(function(data) {
console.log("Data:", data);
});
console.log("After fetch!");
Question: Which will print first in the console: "After fetch!" or "Data:"?
Explain why fetch behaves differently from normal top-to-bottom code execution.
Predict the output of:
console.log("X");
setTimeout(() => console.log("Y"), 1000);
console.log("Z");
Question: Write the order you think will appear.
Run it and confirm. Was your guess correct?
.then().Final Question: Why is it important to understand events and callbacks when working with APIs?