🚀 How JavaScript Runs Internally While revising JavaScript internals, I went through how JavaScript code actually executes step by step. 👉 JavaScript code cannot run without being pushed to the Call Stack. Execution always starts with the creation of the Global Execution Context (GEC), which is pushed to the call stack. 🔹 Global Execution Context GEC has two phases: Memory Phase – variables are allocated memory and initialized Code Phase – code executes line by line 🔹 Web APIs (setTimeout, events, promises) When setTimeout is used: It is not part of JavaScript It runs inside Web APIs The timer starts in Web APIs The Call Stack never waits; remaining synchronous code executes immediately Once the timer completes: The callback is pushed to the Task / Callback Queue 🔹 Promises & Microtask Queue Promises also go to Web APIs After resolving, they move to the Microtask Queue Microtask Queue has higher priority than Task Queue 🔹 Event Loop The Event Loop continuously monitors: Whether the Call Stack is empty Whether Microtask or Task Queues have pending callbacks If the Call Stack is empty: Microtask Queue callbacks are pushed first Then Task Queue callbacks are pushed 🔹 Starvation When there is heavy or infinite promise chaining, microtasks keep getting executed and task queue callbacks may never get a chance to enter the call stack. This situation is called Starvation. #JavaScript #EventLoop #CallStack #AsyncJS #InterviewPreparation
JavaScript Internals: Call Stack, Web APIs, and Event Loop
More Relevant Posts
-
💡 How JavaScript Code Executes (Behind the Scenes) Everything in JavaScript happens inside an Execution Context. You can imagine an execution context as a box with two parts: 1) Memory Component (Variable Environment) - Stores variables and functions as key-value pairs - Variables are stored as undefined - Functions store the entire function code 2) Code Component (Thread of Execution) - This is where the code runs - Code is executed line by line - JavaScript is synchronous and single-threaded What happens when a JavaScript program runs? When the program starts, a Global Execution Context is created. Execution happens in two phases: Memory Creation Phase - JavaScript scans the whole program - Memory is allocated to variables and functions Code Execution Phase - JavaScript executes code line by line - Values are assigned to variables - On function call, a new execution context is created Call Stack - Manages the order of execution - Global Execution Context is pushed first - Function contexts are pushed and popped after execution Understanding execution context helps in mastering hoisting, scope, closures, and async JavaScript. #JavaScript #WebDevelopment #Frontend #React #LearningInPublic
To view or add a comment, sign in
-
-
If you work with JavaScript, you know how often you forget small but important details. I put together a complete JavaScript quick reference guide that covers: – fundamentals – arrays & objects – async / await – DOM manipulation – advanced concepts with real examples It’s meant to be bookmarked and reused. Read here: https://lnkd.in/gNun7kxB
To view or add a comment, sign in
-
⏳ Who Runs First in JavaScript — Promise or Timer? If fetch() and setTimeout() both finish at the same time — which one goes into the call stack first? 🤔 To answer this, let' see how JavaScript actually schedules async work. JavaScript does one thing at a time. When something takes time (API calls, timers, promises), JavaScript delegates the work and continues executing without blocking. So… where does this delegated work go, and how does it come back? 👇 Let's dig more... Call Stack → Executes code one step at a time. Whatever is on top, runs first. Web APIs → Timers (setTimeout, setInterval), fetch, DOM events, console these are not part of JavaScript itself, but are provided by the JS runtime environment (browser / Node). Callback Queue / Microtask Queue → When async work completes: • setTimeout → callback is pushed to Callback Queue • Promises → callback is pushed to Microtask Queue Event Loop → The real hero, its only job is to keep checking: 👉 Is the call stack empty? If yes → move tasks from the queue to the stack (based on priority). What Priority and what about the question? If fetch() (promise) and setTimeout() complete at the same time 👉 Promise callbacks (Microtask Queue) always get priority over timers (Callback Queue). #JavaScript #FrontendDevelopment #WebDevelopment
To view or add a comment, sign in
-
JavaScript – Execution Context Before JavaScript runs even a single line of your code, it prepares a working space for it. That space is called an Execution Context. In simple words: Execution Context is where JavaScript remembers things and runs your code Whenever JavaScript runs: ● Your whole program → one big Execution Context ● Every function call → a new small Execution Context Each one is created in two steps: 1️⃣ Memory Phase ● Variables are created → undefined ● Functions are stored fully 2️⃣ Execution Phase ● Code runs line by line ● Variables get real values ● Functions are executed Example: *** var a = 5; function show() { var b = 3; console.log(a + b); } show(); *** How JavaScript works: ● Creates a global context ◦ a → undefined ◦ show → saved ● Runs code ◦ a = 5 ◦ show() is called → new context is created ● Inside show() ◦ b = 3 ◦ Prints 8 JavaScript manages these contexts using a Call Stack: ● Global goes first ● Each function goes on top ● When a function finishes, it is removed This is why understanding Execution Context helps you: ● Understand hoisting ● Read call stack errors ● Master scope & closures ● Debug with confidence This is how JavaScript thinks before it acts. #Day1 #JavaScript #Frontend #WebDevelopment #LearningInPublic #React #Developers #CareerGrowth
To view or add a comment, sign in
-
Cleaning Up Side Effects in JavaScript — The Pattern Most Bugs Come From Once you understand closures and the JavaScript memory model, the real challenge isn’t identifying side effects — it’s ending them correctly. In JavaScript, side effects like event listeners, timers, and async tasks don’t automatically stop when the function that created them finishes. They live independently and continue to run until you explicitly tell them to stop. This is intentional behavior, not a bug. Professional JavaScript code treats every side effect as a lifecycle. If you add an event listener, you also define when it should be removed. If you start an interval, you decide when it should be cleared. If you kick off async work, you need a way to cancel or ignore it when it’s no longer relevant. This is why cleanup logic should be written at the same time as setup logic. Pairing addEventListener with removeEventListener, setInterval with clearInterval, and async operations with cancellation or guards prevents stale closures and unnecessary memory retention. The rule is simple but powerful: Side effects must have a clear start and a clear end. When you design side effects this way, memory leaks become rare and behavior stays predictable.
To view or add a comment, sign in
-
-
So, you're building projects with JavaScript - and that's awesome. But, let's get real, do you really understand how the "this" keyword works? It's tricky. Its value is all about how a function is called, not where it's defined - that's the key. You see, context is everything here. And, honestly, it's not that hard once you wrap your head around it. The thing is, "this" behaves differently in various contexts - and that's what trips people up. For instance, when you're working with object literals, the "this" keyword refers to the object itself - makes sense, right? But, when you're dealing with function calls, it's a whole different story - thethis keyword can refer to the global object, or even null, depending on how the function is invoked. So, it's essential to understand these nuances to avoid common mistakes. Like, have you ever tried to access a property using "this", only to find out it's undefined? Yeah, that's frustrating. Anyway, if you're just starting out with JavaScript, or revisiting the basics, this post is for you. You'll learn whatthis means in JavaScript, how it behaves in different contexts, and some common pitfalls to watch out for. It's all about mastering the "this" keyword - and trust me, it's worth it. Check out this deep dive: https://lnkd.in/g-tn9CXj #JavaScript #Coding #WebDevelopment
To view or add a comment, sign in
-
Why does 0 == false return true in JavaScript? 😵 If this confuses you, you're not alone. I wrote a guide explaining == vs === and how to avoid common pitfalls that trip up even experienced developers. Link below 👇 https://lnkd.in/dGP2aJZr #JavaScript #CodingTips #WebDev
To view or add a comment, sign in
-
🧠 JavaScript – Scope, Hoisting & this Understanding How JavaScript Works Internally To write better JavaScript, it’s not enough to know what to write we must understand how JavaScript executes code behind the scenes. This is where scope, hoisting, and this become important. 🔹 Scope in JavaScript Scope defines where a variable can be accessed. 🌍 Global Scope Variables declared outside functions or blocks. let appName = "MyApp"; function showName() { console.log(appName); } 👉 Accessible everywhere in the program. 🏠 Local (Function) Scope Variables declared inside a function. function greet() { let message = "Hello"; console.log(message); } 👉 Cannot be accessed outside the function. 📦 Block Scope Variables declared using let and const inside {}. if (true) { let count = 5; } 👉 count is not accessible outside the block. 🔹 Hoisting (Important Concept) Hoisting means JavaScript moves declarations to the top before execution. console.log(a); var a = 10; 👉 Output: undefined (The declaration is hoisted, not the value.) let and const with Hoisting console.log(b); let b = 5; 👉 This causes an error. Why? let and const are hoisted But not initialized (Temporal Dead Zone) 🔹 The this Keyword this refers to the object that is currently using the function. In a Regular Function console.log(this); 👉 Refers to the global object (window in browsers). Inside an Object let user = { name: "Alex", greet() { console.log(this.name); } }; 👉 this refers to the user object. Arrow Functions & this let user = { name: "Alex", greet: () => { console.log(this.name); } }; 👉 Arrow functions do not have their own this. 🧠 Simple Way to Remember Scope → where variables live Hoisting → how JS reads code this → who owns the function Understanding these prevents confusing bugs. ✅ Why This Matters Helps write predictable code Avoids scope-related errors Makes frameworks easier to understand Often asked in interviews If you understand this, you’re thinking like a real JavaScript developer. . . #JavaScript #WebDevelopment #ProgrammingBasics #LearningInPublic #FrontendDevelopment #FullStackJourney
To view or add a comment, sign in
-
-
why react When we have JavaScript.? #javascript #reactjs. . . in react we can create reusable component and included in other pages.but if we are using only javascript we need to add the code in every page..this video explains tat clearly...
To view or add a comment, sign in
-
🚀 New blog post published! Using WebAssembly in Modern JavaScript Projects: A Comprehensive Guide Discover how to integrate WebAssembly into modern JavaScript projects to boost performance, enhance functionality, and build faster web applications. Learn the benefits, use cases, and step-by-step implementation. 👉 Read more: https://lnkd.in/dGyg3Vpx #WebAssembly #JavaScript #WebDevelopment #PerformanceOptimization #WebAssemblyVsJavaScript
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