🚀 How browsers really handle JavaScript (Call Stack + Web APIs + Event Loop) • JavaScript is single-threaded — but your browser is not. What feels like “parallel execution” is actually smart coordination between the Call Stack, Web APIs, and the Event Loop. ✨ The working: The Call Stack executes synchronous JS line by line. When JS hits async work (setTimeout, fetch, DOM events), the browser offloads it to Web APIs. Once the task finishes, the Event Loop decides when it can safely push the callback back into the Call Stack. 💡 Example: setTimeout(fn, 0) does not mean “run immediately.” It means: “Run after the call stack is empty.” Similarly, fetch() goes to Web APIs, and its .then() runs only after the stack is free — even if the network responds fast. What to avoid: ❌ Long synchronous loops (they block the Call Stack) ❌ Assuming async code runs instantly ❌ Heavy CPU work on the main thread (use Web Workers) How to find issues: Open Chrome DevTools → Performance. If you see long “Task” bars, your Call Stack is blocked. If clicks feel delayed, the Event Loop is waiting. Understanding this model is the key to writing asynchronous code and writing performant code. Once this clicks, debugging UI freezes becomes much easier. #javascript #webdevelopment #frontend #SoftwareEngineering #reactjs #coding #programming
JavaScript Execution: Call Stack, Web APIs, Event Loop
More Relevant Posts
-
Built a Vanilla JavaScript CRUD App — Live Demo 🚀 I built a lightweight CRUD application using pure HTML, CSS, and JavaScript, focused on mastering fundamentals instead of relying on frameworks. The app supports: • Create, Read, Update, Delete operations • Data persistence using browser localStorage • Clean, responsive UI • No libraries, no frameworks, no shortcuts This project reinforced how much can be done with plain JavaScript, solid DOM manipulation, and proper state handling. 🔗 Live Demo: https://lnkd.in/dEhuAsJM 🔗 GitHub Repo: https://lnkd.in/dmnCVrEr Sometimes the best way to grow is to strip things down to the basics and make them clean. #JavaScript #WebDevelopment #Frontend #VanillaJS #GitHubPages #LearningByBuilding
To view or add a comment, sign in
-
-
So, you think you know JavaScript. It's all about the Event Loop, right? Not so fast. What happens before your code even gets there is pretty fascinating. Most folks focus on the Event Loop itself, but the journey your code takes to get there is just as important. You've probably memorized terms like scope, closures, and the Temporal Dead Zone - but do you really get what's going on under the hood? It's like having a favorite recipe, but not knowing how the ingredients are sourced. In this series, we're going to break down the entire process, from source code to execution. Let's get real - your code doesn't exist in a bubble. It needs an environment to run in. The ECMAScript 262 spec outlines four key stages: determining the execution environment, parsing the source code, creating meta-objects, and finally, program execution. Simple. But here's the thing: the execution environment is made up of three layers. It's like a matryoshka doll - you've got the Host (think browser or Node.js), the Agent (like a browser tab or Web Worker), and the Realm (which defines the global object, methods, and variables). Understanding these layers is crucial. It explains why browser tabs don't have race conditions - they're isolated, like separate rooms in a house. Workers can't access the main application's global object, because they're in their own little world. And when you override global methods, they're isolated within a Host - like a custom remix of your favorite song. Check it out: https://lnkd.in/ggCaUGKw #JavaScript #EventLoop #ExecutionEnvironment
To view or add a comment, sign in
-
🔄 JavaScript is single-threaded. So how does it handle multiple tasks at once? Meet the Event Loop. It's the unsung hero that keeps your browser from freezing while waiting for an API call. Many developers use setTimeout or fetch daily without knowing what happens under the hood. Here is the architecture that makes non-blocking I/O possible: 1️⃣ Call Stack (The Boss): JavaScript does one thing at a time. It executes functions LIFO (Last In, First Out). If the stack is busy, nothing else happens. 2️⃣ Web APIs (The Assistants): When you call setTimeout or fetch, the browser takes that task out of the Call Stack and handles it in the background (Web APIs). This frees up the stack to keep running your code! 3️⃣ Callback Queue (The Waiting Room): Once the background task is done (e.g., the timer finishes), the callback function is moved to the Queue. It waits there patiently. 4️⃣ The Event Loop (The Traffic Controller): This is the infinite loop. It constantly checks: - "Is the Call Stack empty?" - "Is there something in the Queue?" - If Stack is Empty AND Queue has items 👉 Move item to Stack. Understanding this flow is the key to debugging weird async behavior. Did you know setTimeout(fn, 0) is a hack to defer execution until the stack is clear? #JavaScript #WebDevelopment #EventLoop #CodingInterview #Frontend #SoftwareEngineering
To view or add a comment, sign in
-
-
#A Small Framework I Built a Long Time Ago Some time ago, out of curiosity more than necessity, we built a small JavaScript framework. Not to compete with React or Vue. Not to create the “next big thing”. Just to really understand how modern frontend frameworks work under the hood. That project became mini-framework-z01. It’s a lightweight framework built with plain JavaScript and focused on fundamentals: Virtual DOM abstraction Simple reactive state with subscriptions Client-side routing for SPAs A small event system Component-based structure One intentional choice was keeping things simple. When state changes, the virtual tree is re-rendered and the framework handles DOM replacement efficiently. No complex magic, just clear logic. I don’t actively maintain it today, but it represents an important step in my learning journey. It was the moment I stopped only using frameworks and started building one. #Built with friends and curiosity ❤️ MOHAMED EL FIHRY Omar Ait Benhammou ibrahim el harraq OUSSAMA BENALI If you’re curious about how frontend tools actually work behind the scenes, this kind of project teaches you a lot. Repo: https://lnkd.in/dq2W3cfD #JavaScript #Frontend #LearningByDoing #BuildInPublic #SoftwareEngineering
To view or add a comment, sign in
-
Callbacks are what make JavaScript actually usable. Without them, everything would freeze. JavaScript is single-threaded. If you had to wait for every operation to finish before moving to the next line, your app would be unusable. Click a button? Wait. Fetch data? Wait. Timer? Wait. Callbacks fix this. You pass a function to something (like an event listener or setTimeout), and JavaScript says "cool, I'll call this later" and keeps moving. Your code doesn't block. The page doesn't freeze. The key insight: you're giving up control. The function you pass becomes a callback - you're not calling it, something else is. That's why it's called a "call back" function. Simple concept, massive impact on how JavaScript works. Wrote down how callbacks enable async behavior: https://lnkd.in/d_FmS7XU Thanks to Akshay Saini 🚀 and Namaste JavaScript for breaking this down clearly. If you've been confused about why we pass functions around so much in JS, this might help. #JavaScript #WebDev #Coding #LearningInPublic
To view or add a comment, sign in
-
-
🔥 JavaScript Sets Got Superpowers (That Many Devs Still Don’t Know) Most JavaScript developers still solve set problems using array.filter() or utility libraries. But modern JavaScript now ships native Set methods that make this cleaner, faster, and more expressive. Here’s a real-world example using student toppers (See Below) 🧠 What this gives you ✅ intersection() → students topping both subjects ✅ union() → all toppers without duplicates ✅ difference() → subject-specific toppers ✅ symmetricDifference() → runner-ups (top in only one subject) Why this matters Cleaner than filter + includes No external libraries needed Expresses intent, not mechanics Ideal for search, filters, permissions, ecommerce catalogs ⚠️ These APIs are available in modern runtimes (latest Chrome/Edge, Node.js 22+). If you’re supporting older environments, you may still need a polyfill. #JavaScript #ES2025 #WebDevelopment #Frontend #SET
To view or add a comment, sign in
-
-
Are you accidentally slowing down your JavaScript applications? It’s a common mistake I see in code reviews (and one I’ve made myself). When dealing with multiple independent asynchronous calls, it feels natural to just await them one by one. But as the image on the left illustrates, this creates a "waterfall" effect. Your code has to wait for the first operation to finish before it can even start the second one. ✅ The Better Way: Parallel Execution The solution, shown on the right, is Promise.all(). This function takes an array of promises and fires them off simultaneously. Instead of waiting for the sum of all request times (e.g., 2s + 2s = 4s), you only wait for the slowest single request (e.g., max(2s, 2s) = ~2s). This simple change can drastically improve the performance and user experience of your application. A quick rule of thumb: If the data from request A isn't needed to make request B, they should be running in parallel. Have you caught yourself making this mistake? What’s your favorite JS performance tip? Let me know in the comments! 👇 #JavaScript #WebDevelopment #FrontendDeveloper #CodingTips #SoftwareEngineering #PerformanceOptimization
To view or add a comment, sign in
-
-
DAY 2 | WHY DID JAVASCRIPT EVEN NEED NEW VARIABLES — WHEN VAR WAS ALREADY THERE? 🤔 Before React, before modern apps, JavaScript had only one way to store values — var. It worked. But as code grew, problems showed up 👇 🔹 values changed without warning 🔹 same variable behaved differently in different places. 🔹 understanding the code became confusing Example: PROBLEM WITH var var count = 10; var count = 20; console.log(count); Output=20. This confusion became a real issue when applications started growing bigger. So in 2015, JavaScript introduced let and const. 👉 let — for values that can change 👉 const — for values that should not change Example: ✅ WITH const const count = 10; const count = 20; console.log(count); Output: Error,count has been already declared This change was not for style. It was to make code clear, predictable, and easier to understand. And this is exactly the kind of JavaScript React depends on. 💬 If this explanation makes sense (or if you see it differently), let’s discuss in the comments. #JavaScript #ReactJS #FrontendDevelopment #WebDevelopment #LearnInPublic #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
🤔 Quick question: If JavaScript is so powerful, why is it single-threaded? When I first learned that JavaScript runs on a single thread, my reaction was: “Wouldn’t that make it slow?” Turns out… being single-threaded is actually a design choice, not a limitation 👇 console.log("Start"); while (true) { // imagine a heavy blocking task } console.log("End"); 💡 What’s happening here? JavaScript executes code one task at a time. A blocking operation stops everything else. No other code can run until the current task finishes. This is why JavaScript is called single-threaded. So why would JS be designed this way? - Simpler programming model (no race conditions by default) - Predictable execution order - Perfect fit for the browser (DOM is not thread-safe). Takeaway: JavaScript runs on a single thread, meaning it can do one thing at a time. Asynchronous behavior doesn’t come from multi-threading — it comes from the event loop. #JavaScript #WebDevelopment #FullStack #LearningInPublic
To view or add a comment, sign in
-
🧵 How JavaScript Does 10 Things at Once (While Being Single-Threaded) 🔄 Ever wondered how JavaScript handles API calls, timers, or async tasks without freezing the browser UI? The secret is the Event Loop. Even though JavaScript is single-threaded (it can do only one thing at a time), the Event Loop allows it to be asynchronous and non-blocking. Here’s a simple 4-step breakdown of how it works 👇 1️⃣ Call Stack This is the “Now” zone. JavaScript executes synchronous code here. If a function is in the stack, the engine is busy. 2️⃣ Web APIs / Node APIs When you use `setTimeout`, `fetch`, or DOM events, JavaScript hands them off to the browser/Node environment. This keeps the call stack free so the UI doesn’t freeze. 3️⃣ Callback Queue & Microtask Queue Once async tasks complete, their callbacks wait here. 👉 Promises (Microtasks) always run before timers (`setTimeout`). 4️⃣ Event Loop This is the coordinator. It constantly checks: • Is the Call Stack empty? • If yes → move the next task from the queue to the stack. 🔑 Golden Rule: Avoid blocking the Event Loop with heavy synchronous code — otherwise users will experience laggy interfaces. Learning this really helped me understand async JavaScript better 🚀 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #EventLoop #Programming
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development