1. JavaScript is Single-Threaded
JavaScript uses a single-threaded model, meaning only one operation can be executed at a time on the main thread. This design simplifies code execution but can introduce delays if heavy operations block the thread.
To avoid freezing the browser (e.g., during data fetching or timers), JavaScript uses asynchronous techniques powered by the Event Loop and the browser’s Web APIs.
2. What is the Event Loop?
The Event Loop is the mechanism that allows JavaScript to handle asynchronous operations. It continuously monitors the Call Stack and the Callback (or Task) Queue, ensuring non-blocking execution.
Main Components:
- Call Stack: Where JavaScript runs functions one at a time. If a function is called, it’s added to the stack. Once completed, it’s popped off.
- Web APIs: Provided by the browser (e.g.,
setTimeout
,fetch
, DOM events) to handle tasks outside of the main thread. - Callback Queue: Stores completed async callbacks that are ready to be added to the call stack.
- Event Loop: Keeps checking the call stack. If it’s empty, it pushes the first function in the callback queue onto the stack to be executed.
Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout Callback");
}, 0);
console.log("End");
/*
Output:
Start
End
Timeout Callback
*/
Even with a 0ms
delay, setTimeout
is asynchronous. Its callback is placed in the callback queue and waits until the call stack is empty.
3. Asynchronous Concepts
Callbacks
A callback is a function passed into another function to be executed later. Used heavily in event handling and asynchronous APIs.
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData((data) => {
console.log(data); // Data received
});
Callbacks are simple but can lead to callback hell if nested too deeply.
Promises
Promises provide a cleaner way to handle async operations. They represent a value that may be resolved (fulfilled) or rejected in the future.
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved");
}, 1000);
});
promise.then((result) => {
console.log(result);
});
Async/Await
Introduced in ES2017, async
/await
simplifies Promise-based code to look synchronous, making it easier to read and debug.
async function getData() {
const result = await new Promise((resolve) => {
setTimeout(() => resolve("Async/Await Result"), 1000);
});
console.log(result);
}
getData();
4. JavaScript in the Browser
In browsers, JavaScript interacts with the DOM and listens for events (like clicks, keypresses, etc.). These events are handled asynchronously.
Example: Event Listener
document.querySelector("button").addEventListener("click", () => {
console.log("Button clicked!");
});
The callback runs only when the event is triggered, and it doesn’t block the main thread.
5. Microtasks vs Macrotasks
JavaScript has two queues for asynchronous operations:
- Microtasks: Promise callbacks (
.then
,catch
) andqueueMicrotask()
. - Macrotasks:
setTimeout
,setInterval
, UI rendering tasks.
Microtasks are always executed before the next macrotask in the event loop cycle.
Example:
console.log("Script start");
setTimeout(() => {
console.log("setTimeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("Script end");
/*
Output:
Script start
Script end
Promise
setTimeout
*/
Event Loop Asynchronous Concepts and JavaScript in the Browser
1. What is the primary purpose of the event loop in JavaScript?
2. What is the purpose of the call stack in JavaScript?
3. What is the difference between microtasks and macrotasks?
4. What is the purpose of the Promise constructor in JavaScript?
5. What is the main difference between local storage and session storage?
6. How do cookies differ from local storage and session storage in terms of expiration?
7. What is the primary purpose of the Fetch API in JavaScript?
8. What does the Fetch API return upon making a request?
9. How do you handle the fulfilled state of a Promise in JavaScript?
10. When is session storage cleared in a web browser?
11. In the event loop, where does a setTimeout callback go after the delay has elapsed?
12. Where do Promises get placed in the event loop when they are resolved?
13. How can you handle a rejected Promise in JavaScript?
14. What is a key difference between session storage and local storage?
15. What does the 'await' keyword do in an async function?
16. What type of object does the Fetch API return?
17. How can you handle a Fetch API response in JavaScript?
18. How can you parse JSON data from a Fetch API response?
19. Which storage method can be accessed by both client and server?
20. Which of the following is processed after the microtask queue?