🚀 JavaScript Event Loop in Action — Why setTimeout(0) Doesn't Run Immediately I recently experimented with a small JavaScript snippet to understand how blocking code interacts with timers and the event loop. Here is the code: console.log("Script start"); // Timer with 0ms setTimeout(() => { console.log("0ms timer executed"); }, 0); // Timer with 100ms setTimeout(() => { console.log("100ms timer executed"); }, 100); // Timer with 500ms setTimeout(() => { console.log("500ms timer executed"); }, 500); console.log("Starting heavy computation..."); // Blocking loop for (let i = 0; i < 100000000; i++) {} console.log("Heavy computation finished"); console.log("Script end"); 🔎 What we might expect Many developers assume that setTimeout(..., 0) will execute immediately. But that’s not how JavaScript works. ⚙️ Actual Execution Process 1️⃣ Script starts The synchronous code begins executing on the Call Stack. Script start 2️⃣ Timers are registered The setTimeout functions are handed over to the Web APIs environment. They start counting their timers in the background. 0ms timer 100ms timer 500ms timer But none of their callbacks execute yet. 3️⃣ Heavy synchronous computation starts The large for loop runs on the main thread and blocks it. Starting heavy computation... During this time: JavaScript cannot process any other tasks The call stack remains busy Even if timers expire, their callbacks must wait 4️⃣ Timers expire while the loop is running While the loop is still executing: 0ms timer expires 100ms timer expires Possibly even the 500ms timer But they cannot run yet because the call stack is still occupied. 5️⃣ Loop finishes Heavy computation finished Script end Now the Call Stack becomes empty. 6️⃣ Event Loop starts processing queued callbacks The Event Loop checks the Callback Queue and begins executing timers in order. 0ms timer executed 100ms timer executed 500ms timer executed 🧠 Key Takeaways ✔ JavaScript is single-threaded ✔ Long synchronous tasks block the event loop ✔ setTimeout(0) does not run immediately ✔ Timers only execute after the call stack is empty Understanding this behavior is essential for writing efficient asynchronous JavaScript and avoiding performance issues caused by blocking code. Next on my learning journey: exploring microtasks vs macrotasks and how Promises interact with the event loop. Sarthak Sharma Devendra Dhote #JavaScript #WebDevelopment #EventLoop #AsyncProgramming #FrontendDevelopment
JavaScript Event Loop: setTimeout(0) Delay Explained
More Relevant Posts
-
🚀 JavaScript Event Loop “JavaScript is single-threaded…” 🧵 👉 Then how does it handle timers, API calls, promises, and user interactions so smoothly? What is the Event Loop? 👉 The Event Loop is a mechanism that continuously checks the call stack and task queues, and executes code in the correct order without blocking the main thread. 👉 It ensures JavaScript remains non-blocking and efficient. To Understand Event Loop, You Need 5 Core Pieces: 1️⃣ Call Stack 📚 The Call Stack is a data structure that keeps track of function execution in JavaScript. It follows the Last In, First Out (LIFO) principle. ⚙️ How It Works: >> When a function is called → it is pushed onto the stack >> When the function completes → it is popped off the stack >> The stack always runs one function at a time Example: function greet() { console.log("Hello"); } greet(); 👉 Goes into stack → executes → removed 2️⃣ Web APIs 🌐 👉 Provided by the browser (not JavaScript itself) Handles async operations like: setTimeout, fetch, DOM events.... 3️⃣ Callback Queue (Macrotask Queue) 📥: The Callback Queue (also called Task Queue) is a place where callback functions wait after completing asynchronous operations, until the Call Stack is ready to execute them. ⚙️ How It Works: >> Async function (like setTimeout) runs in background >> After completion → its callback goes to Callback Queue Event Loop checks: > If Call Stack is empty → moves callback to stack > If not → waits 👉 Any callback from async operations like timers, events, or I/O goes into the Callback Queue (except Promises, which go to Microtask Queue). 4️⃣ Microtask Queue ⚡: The Microtask Queue is a special queue in JavaScript that stores high-priority callbacks, which are executed before the Callback Queue. ⚙️How It Works: Execute all synchronous code (Call Stack) Check Microtask Queue Execute ALL microtasks Then move to Callback Queue 5️⃣ Event Loop 🔁 👉 Keeps checking: 👉 “Is the call stack empty?” If YES: >> Execute all microtasks >> Then execute macrotasks Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Output: Start End Promise Timeout 🚀 Key Takeaways: >> JS executes synchronous code first >> Then Microtasks (Promises) completely >> Then Callback Queue (setTimeout, events) >> Event Loop keeps checking and moving tasks #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #Frontend #Coding #Developers #Programming #LearnJavaScript #100DaysOfCode
To view or add a comment, sign in
-
-
🤔 Ever seen code like const { name: fullName } = user or const [first, ...rest] = arr and thought: “Okay... I kind of know what it does, but why is this so common?” That is destructuring and aliasing in JavaScript. 🧠 JavaScript interview question What is destructuring / aliasing in JavaScript, and how is it useful? ✅ Short answer Destructuring lets you extract values from arrays or objects into variables in a shorter, cleaner way. Aliasing means renaming a destructured property while extracting it. That helps you: write less repetitive code set default values pull only what you need avoid variable name conflicts make function parameters easier to read 🔍 Array destructuring With arrays, destructuring is based on position: const rgb = [255, 200, 100]; const [red, green, blue] = rgb; You can skip items or provide defaults: const coords = [10]; const [x = 0, y = 0, z = 0] = coords; // x = 10, y = 0, z = 0 And you can collect the rest: const numbers = [1, 2, 3, 4, 5]; const [first, ...rest] = numbers; // first = 1, rest = [2, 3, 4, 5] 📦 Object destructuring With objects, destructuring is based on property names, not position: const user = { id: 123, name: "Alice", age: 25 }; const { id, name } = user; You can also set fallback values: const { nickname = "Anon" } = user; 🏷️ What aliasing means Aliasing is just renaming during destructuring: const person = { firstName: "Bob", "last-name": "Smith" }; const { firstName: first, "last-name": last } = person; // first = "Bob", last = "Smith" This is useful when: you already have a variable with the same name the original property name is unclear the property name is not convenient to use directly 🧩 Destructuring in function parameters A very common real-world pattern: function printUser({ name: fullName, age }) { console.log(`${fullName} is ${age} years old.`); } Instead of writing user.name and user.age inside the function, you extract what you need immediately. That makes the function signature more self-explanatory. 🌳 Nested destructuring Destructuring can also go deeper into nested data: const data = { user: { id: 42, preferences: { theme: "dark", languages: ["en", "es", "fr"], }, }, }; const { user: { id: userId, preferences: { theme, languages: [primaryLang, ...otherLangs], }, }, } = data; ⚠️ Common thing people mix up Destructuring extracts values. It does not clone deeply. So if the extracted value is an object or array, you are still dealing with references. 💡 Why it is useful in real projects Cleaner code with less repetition Better defaults when data is missing Easier-to-read function parameters Safer naming with aliasing Very handy when working with API responses, props, and config objects That is why destructuring shows up everywhere in React, Node.js, and modern JavaScript codebases. #javascript #webdevelopment #frontend #reactjs #typescript
To view or add a comment, sign in
-
🔥 JavaScript Deep Dive: Understanding this, call(), apply(), and bind() One of the most important concepts in JavaScript is understanding how function context works. Many developers get confused with the behavior of the this keyword and how it changes depending on how a function is called. To control the value of this, JavaScript provides three powerful methods: call(), apply(), and bind(). Understanding these concepts is essential for writing clean, reusable, and predictable JavaScript code, especially when working with callbacks, event handlers, and modern frameworks. 📌 1️⃣ this Keyword In JavaScript, this refers to the object that is executing the current function. const user = { name: "Developer", greet() { console.log(`Hello ${this.name}`) } } user.greet() Output Hello Developer Here, this refers to the user object because the method is called using user.greet(). ⚡ 2️⃣ call() – Execute a function with a specific context The call() method invokes a function immediately and allows us to set the value of this. function greet(){ console.log(`Hello ${this.name}`) } const user = { name: "Developer" } greet.call(user) We can also pass arguments: function greet(city){ console.log(`${this.name} from ${city}`) } const user = { name: "Developer" } greet.call(user, "Meerut") ⚡ 3️⃣ apply() – Similar to call but arguments are passed as an array function greet(city, country){ console.log(`${this.name} from ${city}, ${country}`) } const user = { name: "Developer" } greet.apply(user, ["Meerut", "India"]) ⚡ 4️⃣ bind() – Creates a new function with a fixed this Unlike call() and apply(), the bind() method does not execute the function immediately. Instead, it returns a new function with the specified this value. function greet(){ console.log(`Hello ${this.name}`) } const user = { name: "Developer" } const greetUser = greet.bind(user) greetUser() 💡 Understanding the difference • call() executes the function immediately and arguments are passed normally (comma separated). • apply() also executes the function immediately, but arguments are passed as an array. • bind() does not execute the function immediately. Instead, it returns a new function with the this value permanently bound, which can be executed later. ⚡ Why this concept matters Understanding function context is crucial for: • Reusing functions across objects • Controlling behavior of callbacks • Writing modular and maintainable code • Working effectively with event handlers and asynchronous code Mastering these JavaScript fundamentals helps developers build more predictable and scalable applications. #JavaScript #WebDevelopment #Programming #FrontendDevelopment #Coding #SoftwareDevelopment #DeveloperJourney
To view or add a comment, sign in
-
🚀 Deep JavaScript Concepts Most Developers Don’t Know (But Should!) If you’re already comfortable with closures, promises, and async/await… here are some next-level JavaScript concepts that separate good devs from great ones 👇 🧠 1. Hidden Classes & Shapes (V8 Internals) JavaScript objects are dynamic, but engines like V8 JavaScript engine optimize them using hidden classes. 👉 Objects with the same structure share the same internal layout 👉 Changing structure later (adding/removing props) can deoptimize performance 🔄 2. Event Loop Internals (Microtask vs Macrotask) Not just “event loop” — the priority system matters: 👉 Microtasks (Promises, queueMicrotask) 👉 Macrotasks (setTimeout, setInterval) setTimeout(() => console.log("Macrotask"), 0); Promise.resolve().then(() => console.log("Microtask")); Output: Microtask Macrotask 👉 Microtasks always run before the next macrotask 🧩 3. Deoptimization (Deopt) — Silent Performance Killer Modern engines optimize your code using JIT, but certain patterns force them to fall back: ❌ Changing object shapes ❌ Using "delete" on objects ❌ Accessing out-of-bounds arrays ❌ Mixing types (number + string) 👉 This is called deoptimization, and it can silently slow your app 🧬 4. Garbage Collection (GC) Mechanics JavaScript uses automatic memory management, but not all objects are equal: 👉 Young Generation (fast cleanup) 👉 Old Generation (slower, long-lived objects) Engines like V8 JavaScript engine use Mark-and-Sweep + Generational GC 💡 Memory leaks still happen if references are retained! 🧮 5. Tagged Integers (SMI Optimization) Small integers are stored differently than large numbers: 👉 Fast path for small integers (SMIs) 👉 Large numbers → heap allocation This impacts performance in tight loops ⚡ 🔍 7. Prototype Chain Lookup Optimization Property access doesn’t just check the object: 👉 It walks the prototype chain 👉 Engines cache these lookups too const obj = {}; obj.toString(); // comes from prototype ⚙️ 8. JIT Compilation (Just-In-Time) JavaScript is not just interpreted anymore: 👉 Parsed → Compiled → Optimized at runtime 👉 Engines like Node.js use JIT for speed 💡 Hot code paths get highly optimized 🧨 9. Closures & Memory Retention Closures are powerful but can cause hidden memory issues: function outer() { let bigData = new Array(1000000); return function inner() { console.log("Using closure"); }; } 👉 "bigData" stays in memory because of closure reference! 🔐 10. Temporal Dead Zone (TDZ) "let" and "const" behave differently than "var": console.log(a); // ReferenceError let a = 10; 👉 Variables exist but are not accessible before initialization 🔥 Final Thought Most developers write JavaScript… Few understand how it actually runs under the hood. That difference? 👉 Performance 👉 Scalability 👉 Senior-level thinking #JavaScript #V8 #NodeJS #WebPerformance #SoftwareEngineering #TechDeepDive
To view or add a comment, sign in
-
🚀 JavaScript: The Art of Execution Context & Hoisting (Why it REALLY matters) If you’ve ever wondered why JavaScript behaves the way it does, the answer lies in two core concepts: 👉 Execution Context 👉 Hoisting These aren’t just theory—they define how your code actually runs under the hood. 🧠 1. Execution Context — The Engine Behind Every Line Every time JavaScript runs code, it creates an Execution Context. There are mainly two types: Global Execution Context (GEC) → created when your program starts Function Execution Context (FEC) → created every time a function is invoked 🔄 How it works: Each execution context is created in two phases: 1️⃣ Memory Creation Phase (Hoisting Phase) Variables → stored as undefined Functions → stored with full definition 2️⃣ Code Execution Phase Values are assigned Code runs line by line ⚡ 2. Hoisting — Not Magic, Just Memory Allocation Hoisting is often misunderstood. It doesn’t “move code up”— 👉 it simply means JavaScript allocates memory before execution begins 🔍 Example that explains EVERYTHING console.log(a); // ? console.log(b); // ? console.log(myFunc); // ? var a = 10; let b = 20; function myFunc() { console.log("Hello JS"); } 🧠 Memory Phase: a → undefined b → (in Temporal Dead Zone) myFunc → full function stored 🏃 Execution Phase: console.log(a); // undefined console.log(b); // ❌ ReferenceError console.log(myFunc); // function definition 💣 The TRICKY Part (Arrow Functions vs Normal Functions) console.log(add); const add = () => { return 2 + 3; }; ❓ Output? 👉 ReferenceError: Cannot access 'add' before initialization Why? Because: const variables are hoisted but not initialized They stay in the Temporal Dead Zone (TDZ) So unlike normal functions: console.log(sum); // works function sum() { return 5; } 👉 Function declarations are fully hoisted with definition 👉 But arrow functions behave like variables ❌ 🔥 Key Takeaways ✔ JavaScript creates a new execution context for every function ✔ Memory is allocated before execution starts ✔ var → hoisted as undefined ✔ let / const → hoisted but in TDZ ✔ Function declarations → fully hoisted ✔ Arrow functions → treated like variables 🎯 Why This Matters Understanding this helps you: Debug errors faster ⚡ Write predictable code 🧩 Master interviews 💼 Think like the JavaScript engine 🧠 💡 JavaScript is not weird—you just need to think in terms of execution context. #JavaScript #WebDevelopment #Frontend #Coding #100DaysOfCode #AkshaySaini #Hoisting #ExecutionContext
To view or add a comment, sign in
-
🚨 JavaScript Objects Confused Me… Until I Understood This One Thing When I started learning JavaScript, I thought objects were simple. Then I saw terms like object literals, constructor functions, "this", prototypes, "Object.create()"… And suddenly my brain went: "Wait… what is actually happening here?" 🤯 But once the puzzle clicked, everything started making sense. Here’s the simplest way I now understand JavaScript objects 👇 --- 🔹 1️⃣ Object Literals — The simplest way to create objects const user = { name: "Alex", age: 25 }; Clean. Simple. And used most of the time. --- 🔹 2️⃣ Constructor Functions — Blueprint for multiple objects function User(name, age) { this.name = name; this.age = age; } const u1 = new User("Alex", 25); Here, "this" refers to the new object being created. Think of it like a template for creating many similar objects 🧩 --- 🔹 3️⃣ Prototypes — JavaScript’s hidden superpower Instead of copying methods into every object, JavaScript shares them through prototypes. User.prototype.greet = function() { console.log("Hello!"); }; Now every "User" object can access "greet()" without duplicating memory 🚀 --- 🔹 4️⃣ Object.create() — Direct control over prototypes const person = { greet() { console.log("Hi!"); } }; const user = Object.create(person); This creates an object that inherits directly from another object. Simple concept. Very powerful in practice. --- 🔹 5️⃣ The "let" & "const" confusion with arrays and objects This confused me for a long time 👇 const arr = [1,2,3]; arr.push(4); // ✅ Works But this fails: const arr = [1,2,3]; arr = [4,5,6]; // ❌ Error Why? Because "const" protects the reference, not the content. Objects and arrays are reference types, so their internal values can change. But primitive values cannot: const a = 10; a = 20; // ❌ Error --- 🔥 Once you understand this: • Objects store references • Prototypes enable shared behavior • "this" depends on how a function is called JavaScript suddenly becomes much easier to reason about. And honestly… much more fun to work with. 🚀 --- 💬 If you're learning JavaScript: What concept confused you the most at first? Let’s help each other grow 👇 --- #javascript #webdevelopment #frontenddevelopment #softwaredevelopment #coding #programming #developer #100daysofcode #learnjavascript #codinglife #techlearning
To view or add a comment, sign in
-
JavaScript Was Hard I’d hear from so many people that JavaScript is confusing because of its inconsistencies. But once I learned these concepts, it became so much easier to me : 𝟭. 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 𝗮𝗻𝗱 𝗗𝗮𝘁𝗮 𝗧𝘆𝗽𝗲𝘀: -> Declaration (`var`, `let`, `const`) -> Primitive data types (strings, numbers, booleans, null, undefined) -> Complex data types (arrays, objects, functions) -> Type coercion and conversion 𝟮. 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 𝗮𝗻𝗱 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀: -> Arithmetic operators (+, -, *, /, %) -> Assignment operators (=, +=, -=, *=, /=, %=) -> Comparison operators (==, ===, !=, !==, <, >, <=, >=) -> Logical operators (&&, || , !) -> Ternary operator (conditional operator) 𝟯. 𝗖𝗼𝗻𝘁𝗿𝗼𝗹 𝗙𝗹𝗼𝘄: -> Conditional statements (`if`, `else if`, `else`) -> Switch statement -> Loops (`for`, `while`, `do-while`) -> Break and continue statements 𝟰. 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀: -> Function declaration and expression -> Arrow functions -> Parameters and arguments -> Return statement -> Scope (global scope, function scope, block scope) -> Closures -> Callback functions 𝟱. 𝗔𝗿𝗿𝗮𝘆𝘀 𝗮𝗻𝗱 𝗢𝗯𝗷𝗲𝗰𝘁𝘀: -> Creation and initialization -> Accessing and modifying elements -> Array methods (push, pop, shift, unshift, splice, slice, concat, etc.) -> Object properties and methods -> JSON (JavaScript Object Notation) 𝟲. 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 𝗮𝗻𝗱 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲𝘀: -> Class syntax (constructor, methods, static methods) -> Inheritance -> Prototypal inheritance -> Object.create() and Object.setPrototypeOf() 𝟳. 𝗘𝗿𝗿𝗼𝗿 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴: -> Try...catch statement -> Throwing errors -> Error objects (Error, SyntaxError, TypeError, etc.) -> Error handling best practices 𝟴. 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: -> Callbacks -> Promises (creation, chaining, error handling) -> Async/await syntax -> Fetch API -> setTimeout() and setInterval() 𝟵. 𝗗𝗢𝗠 𝗠𝗮𝗻𝗶𝗽𝘂𝗹𝗮𝘁𝗶𝗼𝗻: -> Selecting DOM elements -> Modifying element properties and attributes -> Creating and removing elements -> Traversing the DOM 𝟭𝟬. 𝗘𝘃𝗲𝗻𝘁 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴: -> Adding event listeners -> Event objects -> Event propagation (bubbling and capturing) -> Event delegation 𝟭𝟭. 𝗠𝗼𝗱𝘂𝗹𝗲𝘀 𝗮𝗻𝗱 𝗠𝗼𝗱𝘂𝗹𝗮𝗿𝗶𝘇𝗮𝘁𝗶𝗼𝗻: -> ES6 modules (import/export) -> CommonJS modules (require/module.exports) -> Module bundlers (Webpack, Rollup) 𝟭𝟮. 𝗕𝗿𝗼𝘄𝘀𝗲𝗿 𝗖𝗼𝗺𝗽𝗮𝘁𝗶𝗯𝗶𝗹𝗶𝘁𝘆 𝗮𝗻𝗱 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲: -> Cross-browser compatibility -> Performance optimization techniques -> Minification and code splitting -> Lazy loading If you're struggling with JavaScript, understanding these topics can make the journey a lot easier! I've Created MERN Stack Guide for beginners to experienced, 𝗚𝗲𝘁 𝘁𝗵𝗲 𝗚𝘂𝗶𝗱𝗲 𝗵𝗲𝗿𝗲 - https://lnkd.in/d6EdjzCs Follow Mohit Decodes on YouTube: https://lnkd.in/dEqvkECV Keep Coding, Keep Building!
To view or add a comment, sign in
-
🚀 setTimeout() vs setInterval() in JavaScript 📘 Definition: setTimeout() is a built-in JavaScript function that executes a given function once after a specified delay (in milliseconds). 👉 Syntax: setTimeout(callbackFunction, delay); 👉 Example: setTimeout(() => { console.log("Runs after 2 seconds"); }, 2000); Key Points: ✔ Executes only once ✔ Delay is in milliseconds (1000ms = 1 second) ✔ Time is not exact, it's a minimum delay 📘 Definition: setInterval() is a built-in JavaScript function that repeatedly executes a function at fixed time intervals. 👉 Syntax: setInterval(callbackFunction, interval); 👉 Example: setInterval(() => { console.log("Runs every 2 seconds"); }, 2000); Key Points: ✔ Executes again and again ✔ Runs at a fixed interval ✔ Continues until manually stopped 🧠 How JavaScript Handles Them (Event Loop Concept) JavaScript is single-threaded, meaning it can execute one task at a time. So how does it handle timers? 👉 Flow: >>>setTimeout / setInterval are handled by Browser APIs >>>After delay, callbacks go to the Callback Queue >>>The Event Loop moves them to the Call Stack when it’s empty That’s why: 👉 Execution time is not guaranteed 👉 It depends on what’s already running ⚠️ Important Difference ✔ setTimeout → Executes once after delay ✔ setInterval → Executes repeatedly at intervals ⚠️ Common Issue with setInterval() If the function takes longer than the interval: >> Calls can overlap >> Performance issues may occur 💡 Better Alternative (Advanced Concept) Using recursive setTimeout() function runTask() { setTimeout(() => { console.log("Controlled execution"); runTask(); }, 2000); } runTask(); ✔ Ensures next execution starts after previous finishes ✔ Gives better control 🛑 Stopping Timers: const id = setInterval(() => { console.log("Running..."); }, 1000); clearInterval(id); Use: ✔ clearTimeout() to stop timeout ✔ clearInterval() to stop interval Real-World Use Cases 🔹 setTimeout(): Delayed popups, API retry logic , Debouncing inputs 🔹 setInterval(): Digital clocks , Live dashboards, Polling servers #JavaScript #AsyncJS #EventLoop #FrontendDevelopment #Coding #WebDevelopment
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 23 A website without interaction is boring… 😴 No clicks No input No response Just static content ❌ 🤔 Real Question How does a website know… 👉 When you click a button? 👉 When you type in an input? 👉 When you scroll? This is where Events come in. 🔥 What is an Event? An event is something that happens in the browser 👉 Click 👉 Hover 👉 Key press 👉 Scroll JavaScript listens to these events and reacts. 🔹 Adding an Event Listener let button = document.querySelector("button") button.addEventListener("click", function() { console.log("Button Clicked") }) 👉 When user clicks → function runs 🔹 Common Events // Click button.addEventListener("click", fn) // Input input.addEventListener("input", fn) // Key press document.addEventListener("keydown", fn) 🔹 Real Example let btn = document.querySelector("button") let heading = document.querySelector("h1") btn.addEventListener("click", function() { heading.innerText = "You clicked the button!" }) 👉 Click → text change 😎 🔹 Event Object JavaScript automatically gives event details button.addEventListener("click", function(event) { console.log(event) }) 📌 You get info like: 👉 Mouse position 👉 Target element 👉 Key pressed 🔥 Real Life Example Think of a doorbell 🔔 You press → sound comes 👉 Action → Reaction Same in JS: User action → Event → Response 🔥 Simple Summary Event → user action addEventListener → listen to event function → response 💡 Programming Rule Websites react to users. Events make that possible. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 Today we are going to analyse the JavaScript microtask queue, macrotask queue, and event loop. A junior developer once asked me during a code review: "Why does Node.js behave differently even when the code looks simple?" So I gave him a small JavaScript snippet and asked him to predict the output. console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); He answered confidently: Start Timeout Promise End But when we ran the code, the output was: Start End Promise Timeout He looked confused. That’s when we started analysing how JavaScript actually works internally. 🧠 Step 1: JavaScript is Single Threaded JavaScript runs on a single thread. It executes code line by line inside the call stack. So first it runs: console.log("Start") → Start console.log("End") → End Now the stack becomes empty. ⚙️ Step 2: Macrotask Queue setTimeout goes to the macrotask queue. Even though timeout is 0ms, it does not execute immediately. It waits in the macrotask queue. Examples of macrotasks: • setTimeout • setInterval • setImmediate • I/O operations • HTTP requests ⚡ Step 3: Microtask Queue Promise goes to the microtask queue. Examples of microtasks: • Promise.then() • Promise.catch() • Promise.finally() • process.nextTick (Node.js) • queueMicrotask() Microtasks always get higher priority. They execute before macrotasks. 🔁 Step 4: Event Loop Now the event loop starts working. The event loop checks: Is the call stack empty? Yes Check microtask queue Execute all microtasks Then execute macrotasks So execution becomes: Start End Promise Timeout Now everything makes sense. 🏗️ Real Production Example Imagine a Node.js API: app.get("/users", async (req, res) => { console.log("Request received"); setTimeout(() => console.log("Logging"), 0); await Promise.resolve(); console.log("Processing"); res.send("Done"); }); Execution order: Request received Processing Logging Why? Because Promise (microtask) runs before setTimeout (macrotask). This directly affects: • API response time • Logging • Background jobs • Queue processing • Performance optimization 🎯 Why Every Node.js / NestJS / Next.js Developer Should Know This Because internally: • Async/Await uses Promises • API calls use Event Loop • Background jobs use Macrotasks • Middleware uses Microtasks • Performance depends on queue execution Without understanding this, debugging production issues becomes very difficult. 💡 Final Thought JavaScript is not just a language. It is an event-driven execution engine. If you understand microtask queue, macrotask queue, and event loop, you don’t just write code — you understand how the runtime thinks. And once you understand the runtime, you start building faster and more scalable systems. #JavaScript #NodeJS #EventLoop #Microtasks #Macrotasks #NextJS #NestJS #SystemDesign #SoftwareEngineering
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