𝐅𝐨𝐫𝐦𝐃𝐚𝐭𝐚 𝐀𝐏𝐈 (𝐓𝐡𝐞 𝐔𝐧𝐜𝐨𝐧𝐭𝐫𝐨𝐥𝐥𝐞𝐝 𝐀𝐫𝐜𝐡𝐢𝐭𝐞𝐜𝐭𝐮𝐫𝐞) 📝 🗑️ I deleted 50 lines of onChange state handlers. Here is why. ✂️ Headline: Tracking every keystroke in a Form just to submit it? You are causing unnecessary re-renders. Let the DOM do the work 🧠 Hey LinkedInFamily, In Frontend System Design, handling Forms is notoriously messy. Whether you use React, Vue, or Vanilla JS, we’ve all fallen into the same architectural trap: The Micromanager Pattern. The Junior Mistake (The Re-render Trap): If a form has 10 inputs (Name, Email, Phone, etc.), developers create 10 state variables. JavaScript: // ❌ The Boilerplate Nightmare (React Example) const [name, setName] = useState(''); const [email, setEmail] = useState(''); // ... 8 more variables // Every single letter typed triggers a UI re-render! 📉 <input onChange={(e) => setName(e.target.value)} /> -- The Flaw: You don't need to know the user's name at the 3rd letter. You only need it when they click Submit. Tracking every keystroke is a waste of CPU cycles and memory. The Senior Architecture (𝐍𝐚𝐭𝐢𝐯𝐞 𝐅𝐨𝐫𝐦𝐃𝐚𝐭𝐚): The browser's DOM already tracks input values perfectly. Why duplicate that data in your JavaScript memory? By using the native FormData API, we can extract the entire form state in ONE line of code, exactly when we need it. 💡 Why is this a System Design Goldmine? 1. Zero Re-renders: Typing doesn't trigger JS calculations. The UI stays buttery smooth. 2. Scalability: If the product team adds 5 new fields to the form tomorrow, you don't have to write a single new line of JS state logic. The FormData catches everything automatically. 3. Framework Agnostic: This native approach works beautifully across React (Uncontrolled Components), Angular, and Vanilla JS. 🛡 My Engineering Takeaway Great architecture avoids duplicating the "Source of Truth". The DOM is already storing what the user typed. Don't fight the platform by pulling data out letter-by-letter. Catch the whole net at the end. Stop micromanaging your inputs. Use FormData. 🛠️✨ Ujjwal Kumar || Software Developer || Web Performance || Clean Code #JavaScript #SystemDesign #FormData #ReactJS #AdvancedJS
Optimize Forms with Native FormData API
More Relevant Posts
-
📌 𝗥𝗲𝘁𝗵𝗶𝗻𝗸𝗶𝗻𝗴 𝗘𝗻𝘂𝗺𝘀 𝗶𝗻 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁. Yes… I said it. If you're building Angular applications, you probably don’t need enums. And in many cases — they’re adding unnecessary complexity. Let’s break it down 👇 🔴 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 #𝟭: 𝗘𝗻𝘂𝗺𝘀 𝗔𝗿𝗲𝗻’𝘁 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Enums don’t exist in JavaScript. So when you write: export enum Status { Active = 1, Inactive = 2 } TypeScript generates a runtime object. Here’s the important part: numeric enums also create reverse mapping in JS: // roughly what gets emitted var Status; (function (Status) { Status[Status["Active"] = 1] = "Active"; Status[Status["Inactive"] = 2] = "Inactive"; })(Status || (Status = {})); Status.Active; // 1 Status[1]; // "Active" ✅ reverse mapping That means: • Extra JavaScript in your bundle • Reverse mapping you likely never use • More code for the browser to parse One enum is harmless. Dozens across a large app? It adds up. 🔴 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 #𝟮: “𝗝𝘂𝘀𝘁 𝗨𝘀𝗲 𝗖𝗼𝗻𝘀𝘁 𝗘𝗻𝘂𝗺” const enum removes runtime output. Sounds perfect. But modern setups using: • Vite • Babel • SWC • Nx (isolatedModules) don’t always support it safely. Now you're choosing between: 1️⃣ Extra runtime code 2️⃣ Tooling limitations Why choose either? 🟢 𝗧𝗵𝗲 𝗦𝗶𝗺𝗽𝗹𝗲𝗿 𝗔𝗹𝘁𝗲𝗿𝗻𝗮𝘁𝗶𝘃𝗲 Use literal types + as const. export const Status = { Active: 1, Inactive: 2, } as const; export type Status = typeof Status[keyof typeof Status]; You still get: ✅ Full type safety ✅ Smaller bundles ✅ Cleaner emitted JavaScript ✅ Better compatibility with modern tooling Same safety. Less magic. 🟢 𝗘𝘃𝗲𝗻 𝗕𝗲𝘁𝘁𝗲𝗿 𝗳𝗼𝗿 𝗔𝗻𝗴𝘂𝗹𝗮𝗿 𝗗𝗿𝗼𝗽𝗱𝗼𝘄𝗻𝘀 Instead of dynamically generating options from enums: Object.values(Status).filter(...) Just define them clearly: export const STATUS_OPTIONS = [ { label: 'Active', value: 1 }, { label: 'Inactive', value: 2 }, ] as const; Simpler. Predictable. More maintainable. 💬 Real question: Are we using enums because they’re the best solution… Or because we learned them first? Team Enum 🔵 or Team Literal Types 🟢 Let’s discuss 👇 #Angular #TypeScript #Frontend #WebDevelopment #CleanCode #Performance #JavaScript #SoftwareEngineering #DeveloperExperience
To view or add a comment, sign in
-
🚀🚀 React Native Architecture Explained { PART 4 } — TurboModules 🚀🚀 If React Native removed the Bridge to enable direct communication between JavaScript and Native code. But that raises an interesting question 👇 If the Bridge is gone… How do Native Modules work now??? This is where TurboModules come into the picture. • TurboModules are the next-generation Native Modules built on top of JSI and are a key part of React Native’s New Architecture. ⚙️ What Are TurboModules? • TurboModules are an improved version of traditional Native Modules. • They allow JavaScript to access native device capabilities faster and more efficiently. • Examples include: 📷 Camera 📍 Location services 📁 File system 🎵 Media access 💳 Payment SDKs • In the old architecture, these modules communicated through the Bridge, which created overhead. • Now with TurboModules, they communicate directly using JSI. 🧠 Simple Mental Model • Old Architecture: JS ⬇ 🌉 Bridge ⬇ Native Module • New Architecture: JS ⬇ ⚡ TurboModule (via JSI) ⬇ Native Code - No JSON conversion. No bridge messaging. Just direct execution. 🔍 What Happens Behind the Scenes? Let’s compare the internal flow. • Old Architecture When JavaScript called a native function: 1️⃣ JS sends instruction 2️⃣ Data converts to JSON 3️⃣ JSON crosses the Bridge 4️⃣ Native module reads message 5️⃣ Native executes function 6️⃣ Response travels back through the Bridge Every call required serialization + messaging. This created unnecessary overhead. • New Architecture with TurboModules With TurboModules: 1️⃣ JavaScript calls a native function 2️⃣ JSI connects directly to the module 3️⃣ Native code executes immediately 4️⃣ Result returns directly to JavaScript No serialization. No bridge. This makes communication significantly faster. ⚡ Lazy Loading — A Huge Performance Boost • Another powerful feature of TurboModules is lazy loading. • In the old architecture: All native modules were loaded when the app launched. Even if they were never used. Example: Your app might load: 📷 Camera module 📍 Location module 📁 File system module —even if the user never opened those features. This increased startup time and memory usage. With TurboModules: • Modules load only when they are needed. Benefits: 🚀 Faster startup 📦 Better memory usage ⚡ Improved efficiency In the next part of this series, we’ll explore: 🎨 Fabric — the new rendering engine that improves UI performance in React Native && 🔗 How JSI, TurboModules, and Fabric Work Together This is where React Native’s UI layer becomes significantly more powerful. Stay tuned 🚀 HappY CodinG!! #ReactNative #MobileDevelopment #SoftwareEngineering #JavaScript #ReactNative #MobileDevelopment #SoftwareEngineering #JavaScript #AppDevelopment #FrontendDevelopment #WebDevelopment #Programming #Coding #Developers #TechCommunity #TechCareers #SoftwareDeveloper #DevCommunity #TechInnovation #Engineering #AndroidDevelopment #iOSDevelopment #CrossPlatform #MobileApps
To view or add a comment, sign in
-
🚀 Introducing ng-ink — Angular components that render directly in your terminal. Npm: https://lnkd.in/gxSGNWKK GitHub: https://lnkd.in/gUdvfXUX Over the past few months, I’ve been exploring how modern CLI tools are built. Something interesting kept showing up again and again… Many popular CLIs are powered by Ink — the React library for building terminal interfaces. Tools like: Gatsby CLI Prisma CLI create-react-app AWS Amplify CLI Vercel CLI Why? Because Ink brings the React component model to the terminal. You get: ⚡ Reactive state 🧩 Composable components 📦 Flexbox layouts 🧠 A clean developer experience And honestly… it just works. 🤔 That got me thinking… Angular developers already have all of this — and in some ways even more powerful tools: ⚡ Signals 🏎 AOT compilation 🧠 Proper Dependency Injection 🔒 Strict templates 🧪 A real testing ecosystem But there was no way to run Angular components in the terminal. So I built ng-ink 🔥 🧠 How it works under the hood Angular’s Renderer2 acts as the abstraction layer between the framework and what it renders to (usually the DOM). In ng-ink, that rendering target becomes a virtual node tree that maps to Ink’s React components. Pipeline: Angular Component (compiled via ngc) → InkRendererFactory (custom RendererFactory2) → InkRenderer (builds an InkNode tree instead of DOM nodes) → scheduleRerender() (microtask debouncing) → buildReactElement() (InkNode → React elements) → Ink.render() → Terminal stdout Meanwhile: ⌨️ Keyboard input 📐 Terminal size 🎯 Focus management 🖱 Cursor control are handled via React hooks inside Ink, then exposed to Angular through injectable services: InputService FocusService TerminalService CursorService ✨ What you get out of the box ✅ Real Angular templates (signals, @if, @for, @defer) 📐 Flexbox layout powered by Yoga (same engine used by React Native) 🧩 Full Dependency Injection support ⚡ AOT compilation via ngc (no JIT tricks) 🧪 renderCli() testing utilities for CLI components ♿ Accessibility via ARIA roles and labels 🛠 create-ngink-app scaffolding Start instantly: ```npx create-ngink-app my-cli-app``` Angular in the terminal was something I really wished existed — so I built it. Curious what the Angular community will build with it 👀 💬 I’d really appreciate your feedback, suggestions, and ideas — feel free to share your thoughts! #Angular #AngularDev #JavaScript #TypeScript #CLI #DeveloperTools #OpenSource #WebDevelopment #Frontend #DX #NodeJS #React
To view or add a comment, sign in
-
-
🚀 Types of Loops in JavaScript and Array Methods (Part:2) 👉 A loop is used to execute a block of code repeatedly until a condition is met. Example: Instead of writing this ❌ console.log("Hello"); console.log("Hello"); console.log("Hello"); You can use a loop ✅ for (let i = 0; i < 3; i++) { console.log("Hello"); } ⚙️ How a loop works A loop has 3 parts: 1️⃣ Initialization → starting point 2️⃣ Condition → when to stop 3️⃣ Increment/Decrement → how it moves JavaScript provides multiple ways to loop through data: 1️⃣ for loop (most common) for (let i = 0; i < 5; i++) { console.log(i); } ✔️ Best when you know how many times to run ✔️ Full control over loop 2️⃣ while loop let i = 0; while (i < 5) { console.log(i); i++; } ✔️ Runs while condition is true ✔️ Useful when iterations are unknown. 3️⃣ do...while loop let i = 0; do { console.log(i); i++; } while (i < 5); ✔️ Runs at least once, even if condition is false. 4️⃣ for...of loop let arr = [10, 20, 30]; for (let value of arr) { console.log(value); } ✔️ Best for arrays ✔️ Gives values directly 5️⃣ for...in loop let obj = { name: "Javascript", age: 20 }; for (let key in obj) { console.log(key); } ✔️ Used for objects ✔️ Gives keys 6️⃣ forEach() (array method) let arr = [10, 20, 30]; arr.forEach((value) => { console.log(value); }); ✔️ Clean and readable ✔️ Only works with arrays 🚀 JavaScript Array Methods (push, pop, shift, unshift) Arrays are powerful… but these 4 methods make them super useful 🔥 🧠 Let’s say we have: let arr = [10, 20, 30]; 1️⃣ push() → Add at the end arr.push(40); console.log(arr); // [10, 20, 30, 40] 👉 Adds element to the end of array 2️⃣ pop() → Remove from the end arr.pop(); console.log(arr); // [10, 20, 30] 👉 Removes the last element 3️⃣ shift() → Remove from the start arr.shift(); console.log(arr); // [20, 30] 👉 Removes the first element 4️⃣ unshift() → Add at the start arr.unshift(5); console.log(arr); // [5, 20, 30] 👉 Adds element to the beginning Looping through Arrays: 1️⃣ for loop (classic way) for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } ✔️ Full control over loop ✔️ Can use break and continue ✔️ Works with any logic 2️⃣ forEach() (modern way) arr.forEach((value, index) => { console.log(value); }); 👉 Automatically loops through array ✔️ Cleaner and more readable ✔️ Less code ❌ Cannot break or stop early #JavaScript #Frontend #WebDevelopment #Coding #LearnInPublic
To view or add a comment, sign in
-
I once saw a "reusable" React <Button /> component that took 24 different boolean props. At that point, it’s not a reusable component. It’s a hostage situation. 🛑🔘 When I first started building React applications, my idea of making a component "reusable" was just adding another if statement and another prop every time I needed it to look slightly different. isPrimary, isSecondary, isLoading, hasRightIcon, makeItBlueButOnlyOnTuesdays... Recently, while building the UI components for the Railway Management System dashboard, I decided to take a step back. I didn't want a messy, tightly-coupled component library. I wanted a system that actually felt good to use. If you want to build a React component library that your team won't secretly hate, here are my 3 golden rules: 💥 1. Stop the "Prop Explosion" (Use ...rest): Stop manually defining every single HTML attribute as a prop. If you are building an Input, just expose the specific custom props you need (like errorText), and spread the rest directly onto the native element: <input {...rest} />. Now your component automatically supports onBlur, maxLength, and aria-labels without you writing 50 lines of boilerplate. 🧱 2. Embrace Compound Components: Instead of passing 10 props to a massive monolithic component like <Modal title="Hi" body="Text" footer="Close" />, break it apart! Use the Compound Component pattern: <Modal> <Modal.Header>Hi</Modal.Header> <Modal.Body>Text</Modal.Body> <Modal.Footer>Close</Modal.Footer> </Modal> This is called "Inversion of Control." It gives the developer using the component complete freedom to swap out the UI without breaking the underlying logic. 🧠 3. Headless Logic is the Future: If a component has highly complex state (like an autocomplete dropdown or a multi-select), separate the brains from the beauty. Write a custom hook (useDropdown) that handles all the keyboard navigation, focus management, and state. Then, let the developer plug that hook into whatever CSS or HTML structure they want. A truly reusable component shouldn't force you to read the source code just to figure out how to use it. What is the worst "reusable" component you’ve ever had to deal with in a codebase? Let’s hear the horror stories below! 👇 Follow RAHUL VIJAYAN for more. #ReactJS #FrontendDevelopment #CleanCode #WebArchitecture #SoftwareEngineering #UIUX #TechCareers
To view or add a comment, sign in
-
-
🚀 1. 𝓡𝓮𝓪𝓬𝓽 𝓟𝓮𝓻𝓯𝓸𝓻𝓶𝓪𝓷𝓬𝓮 : 𝓾𝓼𝓮𝓜𝓮𝓶𝓸 𝓿𝓼 𝓾𝓼𝓮𝓒𝓪𝓵𝓵𝓫𝓪𝓬𝓴 One thing that confused me for a while in React was the difference between useMemo and useCallback. Both are used for performance optimization, and at first they look almost the same. But they actually solve slightly different problems. A simple way to remember it: useMemo → memoizes a value useCallback → memoizes a function Example: const filteredItems = useMemo(() => { return items.filter(item => item.price > 100); }, [items]); const handleClick = useCallback(() => { console.log("clicked"); }, []); Why does this matter? Because React recreates functions and calculations on every render. Most of the time it's fine, but when: 1.calculations are expensive 2.components are large 3.functions are passed to child components you may start seeing unnecessary re-renders.That’s where these hooks help. 𝔻𝕠𝕟’𝕥 𝕠𝕧𝕖𝕣𝕦𝕤𝕖 𝕥𝕙𝕖𝕞. But one important thing I learned: Sometimes adding useMemo everywhere actually makes code harder to read with very little performance benefit. Optimization is useful — but only when there is a real problem to solve. 💡 2. 𝓢𝓶𝓪𝓵𝓵 𝓡𝓮𝓪𝓬𝓽 𝓓𝓮𝓽𝓪𝓲𝓵: 𝓦𝓱𝔂 𝓶𝓪𝓹() 𝓦𝓸𝓻𝓴𝓼 𝓫𝓾𝓽 𝓯𝓸𝓻𝓔𝓪𝓬𝓱() 𝓓𝓸𝓮𝓼𝓷'𝓽 We almost always write something like this: {items.map(item => ( <li key={item.id}>{item.name}</li> ))} But if someone tries this: items.forEach(item => { return <li>{item.name}</li>; }); …it simply doesn't render anything. At first glance both functions loop through arrays, so why does one work and the other doesn’t? The answer is in what they return. map() returns a new array. So React receives something like: [<li>Item1</li>, <li>Item2</li>, <li>Item3</li>] React can render arrays of elements. But forEach() returns undefined. So React basically gets: undefined It’s a small JavaScript detail, but understanding it makes React rendering much clearer. A lot of React concepts become easier once you realize that JSX is just JavaScript returning elements. And there is nothing to render. 🔎 3. 𝓡𝓮𝓪𝓵 𝓟𝓻𝓸𝓫𝓵𝓮𝓶 𝓓𝓮𝓿𝓮𝓵𝓸𝓹𝓮𝓻𝓼 𝓕𝓪𝓬𝓮: 𝓤𝓷𝓷𝓮𝓬𝓮𝓼𝓼𝓪𝓻𝔂 𝓡𝓮-𝓻𝓮𝓷𝓭𝓮𝓻𝓼 𝓲𝓷 𝓡𝓮𝓪𝓬𝓽 One performance issue that appears in many React applications is unnecessary re-renders. Sometimes everything works fine functionally, but components keep rendering more times than expected. Some common reasons I’ve seen: • Passing new function references to child components • Recalculating expensive values on every render • Incorrect dependency arrays in hooks • Storing too much state at higher component levels Example problem: <ChildComponent onClick={() => console.log("clicked")} /> Every render creates a new function reference, so the child component may re-render even if nothing else changed. React performance optimization is less about tricks and more about understanding how React renders UI. #development #frontend #webdevelopment #reactJs Ajay Suneja 🇮🇳 ( Technical Suneja )
To view or add a comment, sign in
-
🚀 React 19: RIP forwardRef! If you’ve ever struggled with the awkward syntax of forwardRef, I have great news. React 19 has officially simplified how we handle Refs. Now, ref is just a standard prop. No more wrapping your components in Higher-Order Components just to access a DOM node. 🛑 The "Old" Way (React 18) You had to wrap your entire component, which messed up your component definition and made TypeScript types a nightmare to write. JavaScript // Complex and boilerplate-heavy const MyInput = forwardRef((props, ref) => { return <input {...props} ref={ref} />; }); ✨ The React 19 Way (Clean & Simple) Just destructure ref from your props like any other value. It’s cleaner, more readable, and much more intuitive. JavaScript // Just a normal functional component! function MyInput({ label, ref }) { return ( <label> {label} <input ref={ref} /> </label> ); } 📊 Quick Comparison: Why this matters FeatureReact 18 (Old)React 19 (New)Passing RefsforwardRef((props, ref) => ...)Standard prop: ({ ref }) => ...DXHigh friction / boilerplateZero friction / NaturalTypeScriptforwardRef<HTMLButtonElement, Props>interface Props { ref: Ref<HTMLButtonElement> }🔥 Bonus Feature: Ref Cleanup Functions React 19 also solved a long-standing issue with third-party libraries (like D3, Google Maps, or Canvas). You can now return a cleanup function directly from a ref callback! JavaScript <div ref={(node) => { if (node) { console.log("DOM Node added"); // Initialize your 3rd party library here } return () => { console.log("Cleanup time!"); // Destroy library instance to prevent memory leaks }; }} /> 💡 Why we love this: Less Boilerplate: Your component tree stays flat and readable. Better TypeScript Support: No more guessing where to put the Generic types. Memory Safety: Native cleanup for DOM-attached libraries without needing an extra useEffect. React 19 is clearly focusing on making the "Developer Experience" as smooth as possible. Are you still using forwardRef, or are you ready to refactor? 👇 #ReactJS #React19 #WebDevelopment #Frontend #JavaScript #CleanCode #ProgrammingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
For years, Angular required NgModules to organize applications. Now? With Standalone Architecture — components are the building blocks directly. Let’s simplify it. 🧠 Old Thinking (Module-Based) Earlier, every component had to belong to a module: Component Declared in NgModule Imported into another NgModule Bootstrapped via AppModule It added structure — but also complexity. 🚀 New Thinking (Standalone) Now you can write: @Component({ selector: 'app-home', standalone: true, imports: [CommonModule], template: `<h1>Hello</h1>` }) export class HomeComponent {} And bootstrap directly: bootstrapApplication(HomeComponent); No AppModule required. 🔎 What Problem Does It Solve? ✅ Reduces boilerplate ✅ Makes code easier to read ✅ Improves tree-shaking ✅ Encourages feature-based structure ✅ Faster onboarding for new developers Large applications become cleaner and more modular. 🧩 JavaScript Concept Behind It Standalone Architecture is inspired by ES Modules in JavaScript. In JavaScript: // user.js export function getUser() {} // app.js import { getUser } from './user.js'; Each file is independent. You import only what you need. Standalone Angular works the same way: Each component declares what it needs directly in imports. No middle layer (NgModule) required. 🎯 Deep Insight Standalone Architecture shifts Angular from: "Module-driven architecture" to "Component-driven architecture" Which aligns Angular more closely with modern JavaScript modular design.| In simple words 👇 Standalone components make Angular: • Simpler • More modular • Closer to native JavaScript module thinking Angular is evolving — and Standalone is a major architectural shift. #Angular #JavaScript #Frontend #WebDevelopment #SoftwareArchitecture
To view or add a comment, sign in
-
-
React Concepts ------------------------- What is Pure Functions? ----------------------- In JavaScript, when functions returns same output when same input is passed is called pure functions. It is like returning same data for same input. So, in pure function output only depend on its input arguments. Pure functions does not produced any side effects as well. Example: -------- addtwoNumber = (a,b)=>{ return a+b; } addtowNumber(2,2); addtowNumber(2,2); addtowNumber(2,2); addtowNumber(2,2); React.memo: ----------- React.memo is a higher-order component (HOC) in React that optimizes the performance of functional components by preventing unnecessary re-renders. It achieves this through a process called memoization. When a functional component is wrapped with React.memo, React will memoize(cache) the rendered output of that component. During subsequent renders, if the props passed to the memoised component are shallowly equal to the props from the previous render, React will skip re-rendering the component and instead reuse the cached output. This can significantly improve performance, especially for components that are frequently re-rendered but whose props often remain the same. HOC: ---- A Higher-Order Component (HOC) in React is an advanced techniue for reusing component logic. It is a function that takes a component as an argument and returns a new, enhanced component. Lazy Loading in React: ---------------------- Lazy loading is a way to delay loading certain parts of the application until they are actually needed. React provides the React.lazy function, which allows you to define components that are loaded dynamically. What is Code Splitting? ----------------------- Code splitting is a technique that breaks down a large JavaScript bundle into smaller chunks that are loaded on demand. Instead of loading the entire application at once, only the code needed for the current view is fetched. This approach reduces initial load times and allows the application to load better. Error boundaries -------------------------- Error boundaries in React are components designed to catch JavaScript error that aoccur within their child component tree, log those errors, and display a fallback UI instead of crashing the entire application. They act as a safety net, preventing unhandled error in a part of the UI from affecting the rest of the application.
To view or add a comment, sign in
-
📌 I went deep into the JavaScript Event Loop. Here's what you need to know — JavaScript is single-threaded. One thing at a time. So how does it handle API calls, timers, and clicks without freezing? That's the Event Loop. 🏗️ 4 pieces working together: ✅ Call Stack Queue — where code runs. LIFO. One function at a time. ✅ Web APIs Queue — browser handles slow work here. setTimeout, fetch, DOM events — all offloaded outside the JS engine. ✅ Microtask Call Stack Queue — Promise callbacks (.then, async/await). Fully drained before anything else moves. ✅ Macrotask Call Stack Queue — setTimeout, setInterval, I/O. One item per loop cycle. 🔄 Exact priority order — on repeat: -Run the Call Stack Queue -Drain ALL Microtasks -Pick ONE Macrotask -Drain ALL Microtasks again -Repeat ⚡ Why this output surprises people: console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")).then(() => console.log("4")); console.log("5"); // Output: 1 → 5 → 3 → 4 → 2 Sync runs first. Microtasks before macrotasks. setTimeout runs last — even at 0ms. This one example covers 80% of interview questions on this topic. 🔬 async/await = Promises underneath async function run() { console.log("A"); await Promise.resolve(); console.log("B"); // Microtask Call Stack Queue } console.log("1"); run(); console.log("2"); // Output: 1 → A → 2 → B Every await pushes the rest of the function into the Microtask Call Stack Queue. ❌ Blocking the Call Stack Queue: while (Date.now() - start < 3000) {} // freezes everything No timers. No clicks. No UI. This is why heavy work belongs in a Web Worker. 🎤 Interview questions — answer these yourself: 1. What is the Event Loop and why does JS need it? 2. Microtask vs Macrotask Call Stack Queue — what's the difference? 3. Why doesn't setTimeout(0) run immediately? 4. Can the Microtask Queue starve the Macrotask Queue? 5. How does async/await relate to the Microtask Queue internally? 6. Where does browser rendering fit in the Event Loop cycle? 🧩 The mental model I keep coming back to: Think of a restaurant kitchen. 🔺 The chef is the Call Stack Queue — cooks one dish at a time, nothing else. 🔺 The oven and timers are the Web APIs Queue — working quietly in the background. 🔺 Urgent verbal orders are the Microtask Call Stack Queue — handled completely between every single dish. 🔺 New tickets from the front of house are the Macrotask Call Stack Queue — come in one at a time, wait their turn. 🔺 The expeditor is the Event Loop — constantly checking all queues and keeping everything moving in the right order. 🔺 The chef never picks up a new ticket until every urgent verbal order is handled first. Drop your answer to Q4 below - #JavaScript #EventLoop #CallStackQueue #Frontend #JSInterviews #LearnInPublic #webdevelopment #interviewprep
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