To truly understand asynchronous JavaScript, we need to look at how JavaScript handles execution behind the scenes using the Call Stack, Web APIs, Callback Queue, and Event Loop.
JavaScript is single-threaded, meaning it executes one task at a time. However, using asynchronous features (like setTimeout, Promises, and fetch API), JavaScript can handle multiple tasks without blocking the main thread.
Let's break this down step by step. 🧐
📌 The Call Stack is a LIFO (Last In, First Out) data structure where JavaScript keeps track of function calls.
function greet() {
console.log("Hello!");
}
function welcome() {
greet();
console.log("Welcome!");
}
welcome();
1️⃣ welcome()
is called → Pushed to the stack
2️⃣ Inside welcome()
, greet()
is called → Pushed to the stack
3️⃣ console.log("Hello!")
executes → Removed from the stack
4️⃣ greet()
completes → Removed from the stack
5️⃣ console.log("Welcome!")
executes → Removed from the stack
6️⃣ welcome()
completes → Removed from the stack
🛑 Problem: The Call Stack executes tasks synchronously (one at a time). If a function takes too long, it blocks other code from running.