JavaScript runs in a single thread, which means it can only do one thing at a time. Why is asynchronous programming important in this context?
Think about what happens when you wait for a file to load or a server to respond.
Asynchronous programming lets JavaScript start a task, like loading data, and then continue running other code without waiting. This prevents the app from freezing and keeps it responsive.
Look at the code below. What will it print to the console?
console.log('Start'); setTimeout(() => console.log('Middle'), 0); console.log('End');
Remember that setTimeout schedules code to run later, even with zero delay.
The synchronous console.log calls run first, printing 'Start' then 'End'. The setTimeout callback runs after the current code finishes, printing 'Middle' last.
Consider this code snippet. What error will it produce when run?
async function fetchData() { let response = await fetch('invalid-url'); let data = await response.json(); console.log(data); } fetchData();
Think about what happens if the URL is wrong or unreachable.
The fetch call fails because the URL is invalid, causing a TypeError indicating the fetch failed.
Which of the following best explains how asynchronous programming improves user experience in web applications?
Think about what happens when a website freezes while loading.
Asynchronous programming lets the app do background work while still responding to user actions, preventing freezing and delays.
You want to fetch JSON data from a URL and log it. Which code snippet correctly does this using async/await?
Remember to await both the fetch and the conversion to JSON.
Option D correctly awaits the fetch and then awaits the response.json() call before logging the data. Other options miss awaiting one or both promises, causing errors or logging promises instead of data.