📌 Concept: How JavaScript Executes Code JavaScript execution finally made sense to me when I stopped asking “what runs first?” and started asking “where does it go?” Here’s the full flow, step by step 👇 1️⃣ Call Stack (Execution starts here) – JS runs synchronous code line by line – One function at a time – If the stack is busy, nothing else runs 2️⃣ Web APIs / Background Tasks – setTimeout, fetch, DOM events – These don’t block the stack – They run outside JS 3️⃣ Queues (Where async waits) 🟡 Microtask Queue (HIGH priority) – Promise.then() – async/await 🔵 Callback / Task Queue (LOW priority) – setTimeout – setInterval 4️⃣ Event Loop (The coordinator) – Checks if Call Stack is empty – Executes ALL microtasks first – Then takes one task from callback queue Important rule: Microtasks always run before timers. That’s why this happens 👇 setTimeout(() => console.log("timer"), 0); Promise.resolve().then(() => console.log("promise")); Output: promise timer Once this clicked, async behavior stopped feeling random. The Event Loop doesn’t make JS fast. It makes JS predictable. What part of async confused you the longest?
Understanding JavaScript Execution Flow with Call Stack and Event Loop
More Relevant Posts
-
🚀 Event Loop Deep Dive — How JavaScript Really Executes Your Code Most developers use async JavaScript every day… but very few truly understand how it actually works under the hood. JavaScript is single threaded, yet it handles: • API calls • timers • promises • user interactions So what’s the secret? 👉 The Event Loop I just published a deep-dive article where I break this down step by step: ✔ How JavaScript executes synchronous code ✔ What really happens inside the Call Stack ✔ Global Execution Context explained visually ✔ Microtasks vs Macrotasks (Promises vs setTimeout) ✔ Why execution order surprises even experienced devs No shortcuts. No magic. Just how JavaScript really works. If you’ve ever been confused by execution order or faced weird async bugs this one’s for you. 📖 Read the full article here: 🔗 https://lnkd.in/dbUCv6N5 #JavaScript #EventLoop #WebDevelopment #Frontend #SoftwareEngineering #AsyncJS #React #NodeJS
To view or add a comment, sign in
-
“JS Fundamentals Series #1: Execution Context & Call Stack” Behind every line of JavaScript lies a hidden world of execution contexts and stacks — let’s uncover it 👇 Whenever a JavaScript program runs, the JS engine creates a Global Execution Context (GEC), a Global Object, and a special this variable. Think of the Execution Context as a big container with two parts: 1. Memory Component 2. Code Component 🔄 The whole JavaScript code gets executed in two phases:- 1. Memory creation phase: All the variables and functions are assigned memory in the form of "key: value" pairs inside the Memory Component. Variables are assigned a special keyword called "undefined" until their value is initialized. Functions are assigned their whole body as it is. 2. Code execution phase: Inside Code Component, each piece of code gets executed, only one command will get executed at a time and won't move onto the next until the current command is executed. Whenever a function is called/invoked, a new Local Execution Context is created inside the Code Component. 📚 Call Stack This is where all the Execution Contexts are executed in a particular order. It follows a principle known as LIFO - Last In First Out. 💡 Why this matters: Understanding the call stack helps me debug recursion errors, async issues, and write cleaner, more predictable code. 🚀 Next up: I’ll dive into Scope Chain & Lexical Environment. Stay tuned! #JavaScript #Frontend #WebDevelopment #NamasteJS #LearningJourney
To view or add a comment, sign in
-
-
🤔 Quick question: If JavaScript is single-threaded, who decides when async code runs? When I first heard about the Event Loop, I imagined something very complex. Turns out… it’s just a coordinator that decides when JavaScript can execute async callbacks 👇 -------------------------------- console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); -------------------------------- Output: - Start - End - Promise - Timeout 💡 High-level mental model: - JavaScript executes synchronous code using the Call Stack - Async tasks are handled by the runtime environment - When the stack is empty, the Event Loop checks: - Microtasks (Promises) - Then macro tasks (setTimeout, events) - It pushes the next callback onto the stack for execution Takeaway: The event loop is what makes asynchronous javascript possible. It doesn’t run code in parallel — it decides when callbacks can run. 👉 Did this execution order surprise you the first time you saw it? #JavaScript #WebDevelopment #FullStack #LearningInPublic
To view or add a comment, sign in
-
🤔 Quick question: When JavaScript runs async code, where does everything actually go? After learning about the Call Stack and Event Loop, I realized something important: JavaScript doesn’t work alone — it collaborates with Web APIs and queues 👇 --------------------------- console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); ---------------------------- Output: - Start - End - Timeout 💡 What happens behind the scenes? - console.log("Start") → pushed to the Call Stack - setTimeout → handed off to Web APIs - console.log("End") → runs immediately Once the Call Stack is empty: - Event Loop checks the Task Queue - setTimeout callback is pushed back to the stack - Callback executes How the pieces fit together Call Stack → executes JavaScript Web APIs → handle timers, DOM events, network calls Queues → hold callbacks waiting to run Event Loop → coordinates everything Takeaway JavaScript executes code using the Call Stack, offloads async work to Web APIs, and uses the Event Loop to decide when callbacks can run. #JavaScript #WebDevelopment #FullStack #LearningInPublic
To view or add a comment, sign in
-
🚀 How JavaScript Executes a Program (Behind the Scenes) Whenever a JavaScript program runs, the engine executes it in two main phases: 1️⃣ Memory Creation Phase Before executing any code, JavaScript sets up memory. Variables are assigned special initial values: var → undefined let and const → reserved in memory (not initialized yet) Function declarations are fully stored in memory. No code is executed yet — this phase is only about allocation. This is why we can sometimes access functions before they appear in the code (thanks to hoisting). 2️⃣ Code Execution Phase Now JavaScript runs the program line by line. Actual values are assigned to variables. When a function is called: A new Execution Context is created. It goes through its own Memory Creation Phase. Then its own Code Execution Phase. Once finished, that execution context is removed. 🧠 What is an Execution Context? An execution context is an environment where JavaScript code is evaluated and executed. There are two main types: Global Execution Context Function Execution Context Each function call creates a new execution context. 📚 Call Stack JavaScript uses a Call Stack to manage execution contexts. The Global Execution Context is pushed first. Every function call is pushed onto the stack. When a function finishes, it is popped off. The stack follows Last In, First Out (LIFO). This ensures JavaScript maintains the correct order of execution. 💡 Key Takeaway Every JavaScript program runs in this order: Global Execution Context is created Memory is allocated Code is executed line by line Function calls create new execution contexts Call Stack manages execution order Contexts are removed after completion
To view or add a comment, sign in
-
-
💡 JavaScript Deep Dive – Global Execution Context ❓ Ever wondered how JavaScript knows what to execute first? The answer starts with the Global Execution Context (GEC). 🔹 What is Global Execution Context? The Global Execution Context is the default environment created when a JavaScript program starts running. ✔ Created only once ✔ Represents the global scope ✔ Stores all global variables & functions 🔹 How JavaScript Creates the GEC JavaScript does NOT start executing code immediately. It first goes through two phases 👇 1️⃣ Memory Creation Phase (Hoisting) Memory is allocated to variables & functions Variables → undefined Functions → stored with full definition Example: var x = 10; function greet() { console.log("Hello"); } At this stage: x → undefined greet → function definition 2️⃣ Code Execution Phase Code runs line by line Values get assigned Functions execute when called Result: x = 10 greet() runs when invoked 🔹 What else lives in Global Execution Context? this keyword In browsers → this points to the window object Global variables become properties of window 🔹 Why JavaScript is Synchronous & Single-Threaded One command at a time One call stack One thread of execution JavaScript finishes one task before starting the next. 🔹 Key Takeaways ✔ GEC is created before execution ✔ Execution happens in two phases ✔ Variables are hoisted as undefined ✔ Functions are fully hoisted ✔ JavaScript runs sequentially 👉 Next Post: Function Execution Context & Call Stack (This is where most interview questions come from 👀) #JavaScript #FrontendDeveloper #WebDevelopment #ReactJS #SoftwareEngineering #TechCareers #LearningInPublic
To view or add a comment, sign in
-
Day #2 – How JavaScript Actually Works Behind the Scenes . Many developers say they hate JavaScript. Not because JavaScript is a bad language. But because they write code without understanding how JavaScript executes it internally. . When the internal working is unclear, JavaScript feels confusing and unpredictable. In reality, JavaScript follows very strict and well-defined rules. . To understand this, let’s look at a simple example. . # Reference Image . At the very beginning, the JavaScript engine creates a Global Execution Context. This context represents the global scope of the program. . During the creation phase, memory is allocated. Variables are initialized with undefined ( let, const, var ). Functions are stored as references. No code is executed in this phase. . After memory allocation, the execution phase begins. The engine starts executing the code line by line. . When a is encountered, it is assigned the value 5. When abc(6) is called, a new Function Execution Context is created. . Inside this function context, num receives the value 6. ans is calculated as 12. The value 12 is returned and assigned to value1. Once the function finishes, its execution context is destroyed. . The same process happens again for abc(a). A new function execution context is created. num receives the value 5. ans becomes 10. The value 10 is returned and stored in value2. . Throughout this entire process, JavaScript uses the Call Stack. Every execution context is pushed onto the stack when it starts. When execution is complete, it is popped off. This ensures that JavaScript always knows which code to execute next. . JavaScript is not random. It is not magical. It is deterministic and rule-based. . When developers understand execution context and the call stack, JavaScript stops feeling confusing and starts feeling logical.
To view or add a comment, sign in
-
-
Most JavaScript developers use functions every day… But very few truly understand what happens before their code runs. Let’s talk about Execution Context. Every time JavaScript runs your code, it creates something called an execution context. There are two main types: 1️⃣ Global Execution Context 2️⃣ Function Execution Context When your file starts running, JavaScript creates the Global Execution Context. Example: var name = "Sadiq"; function greet() { var message = "Hello"; console.log(message + " " + name); } greet(); Before this code executes: Memory is created. Variables are stored (initially as undefined if declared with var). Functions are fully stored in memory. Then execution begins line by line. When greet() is called, a new Function Execution Context is created. That’s why variables inside a function don’t interfere with global ones. Execution Context explains: Why hoisting happens Why scope works the way it does Why some variables are accessible and others aren’t Understanding this changed how I read JavaScript code. Instead of asking: “What is this line doing?” I now ask: “What context is this running in?” Big difference. Are you writing JavaScript… or do you understand how JavaScript is running your code? 👇 What JavaScript concept confused you the most when you started? #JavaScript #FrontendDevelopment #WebDevelopment #SoftwareEngineering #BuildInPublic
To view or add a comment, sign in
-
🚀 Day 3 Not Just Motivation — Real Concepts to Build Strong Technical Understanding (Part 3) JavaScript Concept That Finally Made Everything Clear: Global Execution Context (GEC) Most JavaScript confusion doesn’t come from complex syntax. It comes from not knowing how JavaScript starts executing your code. Before the first line runs, JavaScript does something very important. 👇 It creates the Global Execution Context (GEC). What really happens when a JS file runs? 🔹 Step 1: GEC is created This is the default execution environment for your program. 🔹 Step 2: GEC is pushed into the Call Stack Yes — the Call Stack starts with GEC. And since the Call Stack follows LIFO (Last In, First Out): GEC stays at the bottom until everything finishes. No function can execute unless GEC already exists. GEC works in two phases (this is key) 1️⃣ Memory Creation Phase (Preparation) Memory is allocated before execution var → undefined Functions → full definition stored let / const → exist but uninitialized (TDZ) 👉 This explains hoisting without any mystery. 2️⃣ Execution Phase Code runs line by line Variables get actual values Functions create their own execution contexts Each new context goes on top of the Call Stack And when a function finishes? 👉 Its execution context is popped off the stack (LIFO in action). One subtle but important detail In the global execution context: Browser → this === window Node.js → this === global Why this concept matters Once you truly understand GEC: Hoisting stops being confusing Call Stack behavior makes sense Async concepts feel more logical Debugging becomes easier 📌 Key takeaway JavaScript doesn’t jump into execution. It prepares memory, sets context, pushes GEC to the Call Stack — then starts running your code. If JavaScript ever felt unpredictable, it’s not chaos. It’s a well-defined execution model — once you see it, you can’t unsee it. #JavaScript #ExecutionContext #CallStack #React #Frontend #TechConcepts #LearningInPublic
To view or add a comment, sign in
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