🧠 Deep dive: How fetch() works in JavaScript (and why it replaced XMLHttpRequest) Most of us use fetch() daily, but understanding how it actually works reveals why it was such a big upgrade over XMLHttpRequest. 🔙 The problem with XMLHttpRequest Imperative, state-driven API (readyState, event handlers) Tight coupling between request lifecycle and JS execution Difficult to reason about and scale Poor composability for async flows 🔜 What fetch() does differently fetch() is a Web API that immediately returns a Promise The network request is offloaded to the browser environment JavaScript execution continues without blocking the call stack 🧩 What happens under the hood The returned Promise starts in a pending state .then() / .catch() callbacks are registered internally on the Promise Once the network request completes: The Promise is fulfilled or rejected Its reaction callbacks are queued in the Microtask Queue The Event Loop schedules these microtasks after the call stack is empty, but before macrotasks ⚠️ Subtle but important detail fetch() only rejects on network failures HTTP errors like 404 or 500 still resolve the Promise This forces explicit error handling via response.ok ✨ Why this design matters Predictable async execution Better separation of concerns Easier composition with Promise.all, async/await Cleaner mental model for performance and debugging Understanding async JavaScript at this level completely changes how you reason about APIs, performance, and event loop behavior. Learning internals > memorizing syntax. #JavaScript #AsyncJavaScript #FetchAPI #EventLoop #Promises #WebPerformance #FrontendEngineering #LearningInPublic
Understanding fetch() and its async JavaScript benefits
More Relevant Posts
-
Day 14: Async / Await in JavaScript Promises improved async code… But Async/Await made it beautiful. ✨ Async/Await lets us write asynchronous code that looks like synchronous code. 🔹 What is async? When you add async before a function: 👉 It automatically returns a Promise async function greet() { return "Hello"; } greet().then(res => console.log(res)); Even though we return a string, JavaScript wraps it inside a Promise. 🔹 What is await? await pauses execution until the Promise resolves. async function fetchData() { const data = await fetch("/api/data"); console.log(data); } 👉 await can only be used inside an async function. 🔹 Error Handling with try/catch async function getData() { try { const res = await fetch("/api/data"); const data = await res.json(); console.log(data); } catch (error) { console.log("Error:", error); } } Much cleaner than multiple .then().catch() chains. 🔥 Why Async/Await is Better? ✅ Cleaner & more readable ✅ Avoids Promise chaining complexity ✅ Easier error handling ✅ Looks synchronous but runs asynchronously #Remeber :Important Interview Point Even with await, JavaScript is still single-threaded. Async/Await works because of: ✔️ Promises ✔️ Event Loop ✔️ Microtask Queue #JavaScript #AsyncAwait #Promises #webdevelopment #LearnInPublic
To view or add a comment, sign in
-
Did you know that when you use an array inside a JavaScript template literal, it doesn’t behave like an array at all? If you write something like: `Stack: ${['React', 'Node', 'TypeScript']}` you might expect JSON-style output or the array structure. But JavaScript actually produces: "Stack: React,Node,TypeScript" That’s because template literal interpolation triggers implicit coercion: .toString() → .join(',') This isn’t a quirk — it’s part of the language design, and arrays have always been stringified using commas. Where this is useful There are a few scenarios where this implicit join is convenient: 1 - quick logging or debugging 2 - passing arrays into string-based utilities 3 - small helper functions where formatting doesn’t matter, etc. Where it becomes risky In more sensitive areas — UI text, error messages, URLs, file paths, nested arrays — this implicit join can lead to subtle formatting bugs or unreadable output, especially if you didn’t intend commas. My recommendation For clarity and predictability in production code, being explicit is usually the better choice: `Technologies: ${tech.join(', ')}` Making the formatting intentional helps avoid surprises and keeps code easier to understand for everyone reading it. #JavaScript #React #WebDevelopment #FrontendEngineering
To view or add a comment, sign in
-
-
Day 62 of me reading random and basic but important dev topicsss..... Today I read about the Resource Loading in JavaScript...... In our day-to-day work building interfaces with React or other modern frameworks, it's easy to take module bundlers for granted. But what happens when we need to dynamically inject a third-party script......like an analytics tracker, a payment SDK, or a support widget.....on the fly? Understanding the vanilla DOM events onload and onerror is a must for any robust front-end architecture. 1. The Dynamic Injection Adding a script dynamically is straightforward: let script = document.createElement('script'); script.src = "third-party.js"; document.head.append(script); But we can't just invoke its functions immediately. The browser needs time to fetch and execute it. 2. script.onload (The Success Path) This event triggers after the script has successfully loaded and executed. This is our green light to safely use the newly available variables or functions. 3. script.onerror (The Failure Path) If the script 404s or the server is down, onerror catches it. However, keep in mind: we won't get HTTP status codes (like 404 or 500) here, just a notification that the network request failed. Loading vs. Execution Here is where we get tripped up: onload and onerror only track the network loading phase. If a script downloads successfully but contains a syntax or runtime error during execution, onload will still fire! To catch those internal execution bugs, we need a different tool entirely: the window.onerror global handler. Keep Learning!!!!! #JavaScript #WebDevelopment #FrontendDev #React #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 12: Promises in JavaScript Callback Hell made async code messy… 😵💫 So JavaScript introduced something better — #Promises 🔹 What is a Promise? A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It has 3 states: 🟡 Pending 🟢 Fulfilled 🔴 Rejected 🔹 Basic Example const promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Data fetched successfully"); } else { reject("Error occurred"); } }); promise .then(result => console.log(result)) .catch(error => console.log(error)); 🔹 Why Promises are Better than Callbacks? ✅ Avoid Callback Hell ✅ Cleaner chaining using .then() ✅ Better error handling with .catch() ✅ More readable async flow 🔹 Promise Chaining fetchData() .then(data => processData(data)) .then(result => saveData(result)) .catch(error => console.log(error)); 👉 Each .then() returns a new promise 👉 Errors bubble down to .catch() 🔥 Why Important? ✔️ Core concept before learning async/await ✔️ Frequently asked in interviews ✔️ Used in APIs, fetch, database calls #Javascript #Promises #Webdevelopment #frontend #LearnInPublic
To view or add a comment, sign in
-
🚀 𝗙𝗶𝗿𝘀𝘁 - 𝗖𝗹𝗮𝘀𝘀 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 In JavaScript, functions are first-class values. That means the language allows functions to be treated the same way as any other value. Practically, this gives us three abilities: • assign a function to a variable • pass a function as an argument • return a function from another function Example:- 1. when assigned as a value const sayHi = function () console.log("Hi"); } => 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘄𝗵𝘆 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗲𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀, 𝗮𝗻𝗼𝗻𝘆𝗺𝗼𝘂𝘀 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀, 𝗮𝗻𝗱 𝗮𝗿𝗿𝗼𝘄 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗻𝗼𝘁 𝘀𝗽𝗲𝗰𝗶𝗮𝗹 𝗰𝗮𝘀𝗲𝘀 , 𝘁𝗵𝗲𝘆’𝗿𝗲 𝗷𝘂𝘀𝘁 𝘃𝗮𝗹𝘂𝗲𝘀. 2. function passed as an argument function executeFunc (callback) { callback(); } executeFunc(sayHi) => 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘁𝗵𝗲 𝗳𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻 𝗳𝗼𝗿 𝗰𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀, 𝗲𝘃𝗲𝗻𝘁 𝗵𝗮𝗻𝗱𝗹𝗲𝗿𝘀, 𝗮𝗻𝗱 𝗮𝘀𝘆𝗻𝗰 𝗰𝗼𝗱𝗲. 𝗧𝗵𝗲 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗶𝘀 𝗷𝘂𝘀𝘁 𝗯𝗲𝗶𝗻𝗴 𝗽𝗮𝘀𝘀𝗲𝗱 𝗹𝗶𝗸𝗲 𝗱𝗮𝘁𝗮. 3. Returning from another function function outer() { return function inner() { console.log("Inner function executed"); }; } const fn = outer(); fn(); => 𝗧𝗵𝗶𝘀 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿 𝗲𝗻𝗮𝗯𝗹𝗲𝘀 𝗰𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗮𝗻𝗱 𝗵𝗶𝗴𝗵𝗲𝗿-𝗼𝗿𝗱𝗲𝗿 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 (𝗺𝗮𝗽, 𝗳𝗶𝗹𝘁𝗲𝗿, 𝗿𝗲𝗱𝘂𝗰𝗲). Most JavaScript patterns work because functions can be passed around like data. First-class functions are the rule that makes that possible. #Javascript #Functions #WebDevelopment #Frontend
To view or add a comment, sign in
-
-
📌 Understanding parseInt() in JavaScript When working with user inputs, APIs, or form data, values often come as strings. To convert those string values into integers, JavaScript provides the parseInt() method. 👉 What does parseInt() do? 🔹 parseInt() converts a string into an integer number. 👉 In simple terms: It extracts a number from a string and converts it into an integer. 💠 Specifying the radix avoids unexpected behavior and ensures consistent results. 💠 Number() requires the entire string to be numeric. 💠 parseInt() extracts the integer part. ✅ Best Practice ✔ Always pass the radix (usually 10) ✔ Validate results using Number.isNaN() parseInt() is a simple yet powerful method that helps convert string data into usable integers — especially when handling user input or processing external data. #JavaScript #WebDevelopment #Frontend #CodingTips #LearnJavaScript
To view or add a comment, sign in
-
-
Why does JavaScript even have closures? Why not just write simple functions instead of this complex syntax? At first glance, this question may seem dismissive, but it actually delves into a profound topic. A "simple function" typically: - Executes - Returns a value - Loses all local state once it finishes This model works for pure, short-lived logic. However, most JavaScript code is not short-lived. The real problem closures solve is that modern JavaScript requires functions that: - Run later (callbacks, events) - Run repeatedly - Run asynchronously - Still remember what happened before Without closures, a function would forget everything once it exits. Closures allow a function to: - Capture variables from its outer scope - Maintain access to them even after the outer function has returned This is not merely about syntax; it’s about preserving state over time. The idea of “just use globals” is problematic. Without closures, we would have to: - Store state in global variables - Pass state manually everywhere - Rely heavily on classes for simple problems These approaches lead to: - Tight coupling - Hard-to-debug bugs - Code that doesn’t scale Closures provide a clean and safe solution to these issues. Real features built on closures include: - Event listeners - setTimeout / async callbacks - Debounce & throttle - Function factories - State management patterns in frameworks Closures are not optional; they are foundational. The key takeaway is that closures exist because JavaScript needs a way to keep state without resorting to globals or classes. Once this concept is grasped, closures become less about complexity and more about necessity. #JavaScript #Closures #FrontendInterviews #SoftwareEngineering #WebDevelopment #JSConcepts
To view or add a comment, sign in
-
📌 Understanding JSON.parse() in JavaScript In JavaScript, data often travels between systems in JSON (JavaScript Object Notation) format — especially when working with APIs. To use that data inside your application, JavaScript provides the JSON.parse() method. 👉 What does JSON.parse() do? 🔹 JSON.parse() converts a JSON string into a JavaScript object. 👉 In simple terms: 🔹 It helps JavaScript understand and work with JSON data. 👉 Example Explanation: 🔹 The API response is a string 🔹 JSON.parse() converts it into an object 🔹 Now we can access properties using dot notation 👉 Why is JSON.parse() important? 🌐 Used when handling API responses 💾 Converts data from localStorage / sessionStorage 🔄 Helps transform string data into usable objects 🚀 Essential for backend–frontend communication 💠 Common Error to Watch Out For 🔹 JSON.parse() only works on valid JSON. 🔹 Invalid JSON will throw an error. 🔹 JSON.parse("{name: 'Hari'}"); // ❌ Error ✔ Correct JSON format: JSON.parse('{"name":"Hari"}'); // ✅ JSON.parse() is a fundamental JavaScript method that plays a key role in real-world applications, especially while working with APIs and stored data. #JavaScript #WebDevelopment #Frontend #JSON #CodingTips #LearnJavaScript
To view or add a comment, sign in
-
-
A lot of developers think 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴, 𝗳𝗲𝘁𝗰𝗵, 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁 are part of JavaScript. 𝗧𝗵𝗲𝘆’𝗿𝗲 𝗻𝗼𝘁. They’re 𝗪𝗲𝗯 𝗔𝗣𝗜𝘀 — provided by the browser (or runtime) to the 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗲𝗻𝗴𝗶𝗻𝗲. JavaScript itself? It’s a 𝘀𝗶𝗻𝗴𝗹𝗲-𝘁𝗵𝗿𝗲𝗮𝗱𝗲𝗱, 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 language. 𝗧𝗶𝗺𝗲, 𝗧𝗶𝗱𝗲 𝗮𝗻𝗱 𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 𝘄𝗮𝗶𝘁 𝗳𝗼𝗿 𝗻𝗼𝗻𝗲 - A Wise Man (Idk who said it but I'm sure he was wise) So how does async work? 👇 • The JS engine executes code line by line. • When it hits 𝗳𝗲𝘁𝗰𝗵 𝗼𝗿 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁, 𝘁𝗵𝗲 𝗯𝗿𝗼𝘄𝘀𝗲𝗿 𝘁𝗮𝗸𝗲𝘀 𝗼𝘃𝗲𝗿. • Once the task completes, the result is pushed to the event loop - can be the 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗤𝘂𝗲𝘂𝗲 𝗼𝗿 𝘁𝗵𝗲 𝗠𝗮𝗰𝗿𝗼. • The callback/promise gets executed when the 𝗰𝗮𝗹𝗹 𝘀𝘁𝗮𝗰𝗸 𝗶𝘀 𝗳𝗿𝗲𝗲. So technically… JavaScript isn’t “naturally asynchronous” It’s synchronous — powered by async capabilities from its environment. 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗿𝘂𝗻𝘁𝗶𝗺𝗲𝘀 = 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗔𝗣𝗜𝘀. Browser ≠ Node ≠ Deno A few more 𝗪𝗲𝗯 𝗔𝗣𝗜𝘀 we use often - 𝘥𝘰𝘤𝘶𝘮𝘦𝘯𝘵, 𝘸𝘪𝘯𝘥𝘰𝘸, 𝘩𝘪𝘴𝘵𝘰𝘳𝘺, 𝘭𝘰𝘤𝘢𝘵𝘪𝘰𝘯, 𝘭𝘰𝘤𝘢𝘭𝘚𝘵𝘰𝘳𝘢𝘨𝘦, 𝘴𝘦𝘴𝘴𝘪𝘰𝘯𝘚𝘵𝘰𝘳𝘢𝘨𝘦, 𝘯𝘢𝘷𝘪𝘨𝘢𝘵𝘰𝘳 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘦𝘳𝘳𝘰𝘳 (𝘤𝘰𝘯𝘴𝘰𝘭𝘦 𝘪𝘴 𝘵𝘩e 𝘈𝘗𝘐, 𝘦𝘳𝘳𝘰𝘳() 𝘪𝘴 𝘵𝘩𝘦 𝘮𝘦𝘵𝘩𝘰𝘥), 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘥𝘪𝘳 𝘧𝘴, 𝘱𝘳𝘰𝘤𝘦𝘴𝘴, 𝘩𝘵𝘵𝘱, 𝘦𝘵𝘤. #JavaScript #WebDevelopment #EventLoop #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
great information