Angular is finally making Fetch API the default. It was long overdue. Let me explain what’s changing and why it matters. 🔍 WHAT ARE FETCH AND XHR? XMLHttpRequest (XHR) has been the backbone of HTTP requests in browsers since the early 2000s. It’s callback-based, imperative, and designed for a different era of JavaScript. Fetch API arrived in 2015 — Promise-based, composable, and built for the modern async/await world we actually live in. Both do the same job. But how they do it is very different. ⚡ KEY DIFFERENCES 𝗘𝗿𝗿𝗼𝗿 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 XHR fires onerror on failure. Fetch only rejects on network-level errors — a 404 or 500 still resolves. You must check response.ok manually. Easy gotcha. 𝗦𝘁𝗿𝗲𝗮𝗺𝗶𝗻𝗴 Fetch exposes response.body as a ReadableStream. XHR gives you the whole payload or nothing. 𝗨𝗽𝗹𝗼𝗮𝗱 𝗣𝗿𝗼𝗴𝗿𝗲𝘀𝘀 XHR wins here. xhr.upload.onprogress gives you byte-level tracking. Fetch has no upload progress API — still the main reason to keep XHR around for file uploads. 𝗖𝗮𝗻𝗰𝗲𝗹𝗹𝗮𝘁𝗶𝗼𝗻 XHR has xhr.abort(). Fetch uses AbortController — more composable, one controller can cancel multiple requests. 𝗞𝗲𝗲𝗽𝗮𝗹𝗶𝘃𝗲 Fetch supports { keepalive: true } — requests complete even after the page closes. Perfect for analytics. XHR dies on unload. 𝗡𝗼𝗱𝗲.𝗷𝘀 𝗦𝘂𝗽𝗽𝗼𝗿𝘁 This is the big one. XHR is browser-only. Fetch is native in Node.js 18+. 🅰️ WHY ANGULAR 22 MAKES FETCH THE DEFAULT Angular has been investing heavily in SSR and hydration. And here’s the problem XHR creates: it doesn’t exist in Node.js natively. Every Angular SSR setup using XHR needed polyfills or mocks just to run on the server. That’s fragile, adds complexity, and breaks the isomorphic code story. Fetch just works — same API, same code, running on both server and browser. This matters because: → HttpClient’s transfer cache (server fetches data once, browser reuses it during hydration) integrates cleanly with Fetch → Streaming responses open the door for better SSR performance patterns → keepalive enables reliable analytics on unload — something modern apps need → No more polyfill gymnastics for Node environments XHR isn’t gone — you can still scope it per-route where you need upload progress. But Fetch is now the default engine powering HttpClient. #Angular #WebDevelopment #JavaScript #Frontend #SSR #TypeScript #AngularDeveloper
Angular makes Fetch API the default
More Relevant Posts
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝘀 𝘀𝗶𝗻𝗴𝗹𝗲-𝘁𝗵𝗿𝗲𝗮𝗱𝗲𝗱. So how does your UI stay responsive while a fetch() is running? Most devs say "async/await". That's not an answer. That's a keyword. Here's what actually happens. 👇 ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗿𝗮𝗰𝗲 𝗮 𝘀𝗶𝗻𝗴𝗹𝗲 𝗳𝗲𝘁𝗰𝗵() 𝗰𝗮𝗹𝗹 𝘁𝗵𝗿𝗼𝘂𝗴𝗵 𝘁𝗵𝗲 𝗲𝗻𝘁𝗶𝗿𝗲 𝗲𝗻𝗴𝗶𝗻𝗲: 𝗦𝘁𝗲𝗽 𝟭 — fetch() hits the Call Stack. The JS engine sees it, pushes it on the stack. But fetch() is not pure JS — it's a Web API. 𝗦𝘁𝗲𝗽 𝟮 — The Call Stack offloads it to the Web API layer. The network request leaves JavaScript entirely. Your browser (or Node.js libuv) handles it in a separate thread. The Call Stack is now FREE. UI stays responsive. 𝗦𝘁𝗲𝗽 𝟯 — Response arrives. Callback enters the Task Queue. The Web API layer puts your .then() or await callback into the appropriate queue and waits. 𝗦𝘁𝗲𝗽 𝟰 — The Event Loop checks both queues. Microtask Queue first (Promise.then, MutationObserver). Drain it completely. Then take ONE callback from the Task Queue. 𝗦𝘁𝗲𝗽 𝟱 — Callback pushed onto the Call Stack. Executed. Your data is now in your component. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗲 𝗽𝗮𝗿𝘁 𝗺𝗼𝘀𝘁 𝗱𝗲𝘃𝘀 𝗺𝗶𝘀𝘀: "Non-blocking" doesn't mean JavaScript runs in parallel. It means the blocking work is delegated to something that CAN run in parallel — Web APIs, OS threads, libuv. JavaScript itself never leaves the single thread. The illusion of concurrency comes from the queue system. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘄𝗵𝘆: → A long synchronous loop BLOCKS your UI (it holds the Call Stack and the Event Loop never runs) → An awaited fetch() does NOT block your UI (it's off the Call Stack within microseconds) → CPU-heavy work should go in a Web Worker (move it off the main thread entirely) ━━━━━━━━━━━━━━━━━━━━━━━ The whiteboard above shows the full flow visually. Save it + this explanation as a pair. 📌 Interview question: "Is JavaScript asynchronous?" Correct answer: No — it's single-threaded and synchronous. Async behavior comes from the runtime environment around it. Drop a 🔥 if this clicked for you today. #JavaScript #FrontendDevelopment #ReactJS #NodeJS #SoftwareEngineering #OpenToWork #ImmediateJoiner
To view or add a comment, sign in
-
-
#js #17 **Destructuring Objects in Javascript** Object destructuring in JavaScript lets you extract properties from an object and assign them to variables in a clean way. 🔹 Basic Syntax const { key1, key2 } = object; 👉 Variable names must match the property names. 🔹 1. Simple Example const user = { name: "Rahul", age: 25 }; const { name, age } = user; console.log(name); // Rahul console.log(age); // 25 🔹 2. Rename Variables const user = { name: "Rahul", age: 25 }; const { name: userName, age: userAge } = user; console.log(userName); // Rahul console.log(userAge); // 25 👉 name: userName → rename variable 🔹 3. Default Values const user = { name: "Rahul" }; const { name, age = 18 } = user; console.log(age); // 18 (default) 🔹 4. Nested Object Destructuring const user = { name: "Rahul", address: { city: "Mumbai", pincode: 400001 } }; const { address: { city, pincode } } = user; console.log(city); // Mumbai console.log(pincode); // 400001 🔹 5. Extract + Rename Nested const user = { address: { city: "Delhi" } }; const { address: { city: userCity } } = user; console.log(userCity); // Delhi 🔹 6. Rest Operator (...) const user = { name: "Rahul", age: 25, country: "India" }; const { name, ...rest } = user; console.log(name); // Rahul console.log(rest); // { age: 25, country: "India" } 🔹 7. In Function Parameters function greet({ name, age }) { console.log(`Hello ${name}, age ${age}`); } greet({ name: "Amit", age: 22 }); 🔹 8. Real Use Case (React Props) In React: function User({ name, age }) { return <h1>{name} - {age}</h1>; } 👉 Directly destructuring props makes code cleaner. 🔥 Key Points Uses {} instead of [] Property names must match (or rename them) Supports: default values nested objects rest operator Very common in React & modern JavaScript #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
𝗥𝗲𝗮𝗰𝘁 𝗶𝗻 𝟮𝟬𝟮𝟲: 𝗜𝘁’𝘀 𝗡𝗼𝘁 𝗝𝘂𝘀𝘁 𝗮 𝗟𝗶𝗯𝗿𝗮𝗿𝘆 𝗔𝗻𝘆𝗺𝗼𝗿𝗲 React has evolved and so should the way we think about it. In 2026, React is no longer just about components, hooks, and state. It’s a full ecosystem designed for building high-performance, scalable, production-grade applications. If you're still treating React as a purely client-side library, you're already falling behind. 𝗪𝗵𝗮𝘁’𝘀 𝗖𝗵𝗮𝗻𝗴𝗲𝗱 (𝟮𝟬𝟮𝟰 → 𝟮𝟬𝟮𝟲) React has shifted to a server-first architecture: ✔ Server Components (RSC) — Default rendering on the server → smaller bundles, faster apps ✔ Server Actions — Backend logic directly inside components ✔ Streaming & Suspense — Instant, progressive UI loading ✔ Concurrent Rendering (Stable) — Smarter, smoother UI updates ✔ React Compiler (Emerging) — Automatic performance optimizations 𝗧𝗵𝗲 𝗿𝗲𝗮𝗹𝗶𝘁𝘆: Fully client-heavy React apps are no longer the standard. 𝗧𝗵𝗲 𝗠𝗼𝗱𝗲𝗿𝗻 𝗥𝗲𝗮𝗰𝘁 𝗦𝘁𝗮𝗰𝗸 React alone isn’t enough anymore. A production-ready setup looks like: • Next.js (App Router + RSC) • TypeScript (non-negotiable) • Tailwind CSS • Server Actions / React Query • Edge deployments (Vercel, etc.) • Lightweight state management (Zustand) Overengineering with Redux for every project? That mindset is outdated. 𝗧𝗵𝗲 𝗥𝗲𝗮𝗹 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗥𝗼𝗮𝗱𝗺𝗮𝗽 𝗙𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻𝘀 HTML, CSS, JavaScript (ES6+), async patterns 𝗖𝗼𝗿𝗲 𝗥𝗲𝗮𝗰𝘁 Components, props, hooks, forms 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗥𝗲𝗮𝗰𝘁 Custom hooks, Context API, performance, error boundaries 𝗠𝗼𝗱𝗲𝗿𝗻 𝗥𝗲𝗮𝗰𝘁 (𝗖𝗿𝗶𝘁𝗶𝗰𝗮𝗹) Server Components, Suspense, Server Actions, Next.js routing 𝗘𝗰𝗼𝘀𝘆𝘀𝘁𝗲𝗺 TypeScript, APIs, authentication, deployment Most developers stop at hooks. That’s just the beginning in 2026. 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀 ✔ Prefer server-side data fetching ✔ Keep client components minimal ✔ Avoid unnecessary state ✔ Write clean, reusable components ✔ Prioritize performance from day one Heavy JS bundles = lost users. 𝗛𝗼𝗻𝗲𝘀𝘁 𝗧𝗿𝗮𝗱𝗲-𝗼𝗳𝗳𝘀 𝗣𝗿𝗼𝘀 ✅ Massive ecosystem ✅ High performance (with RSC) ✅ Flexibility at scale 𝗖𝗼𝗻𝘀 ❌ Steep learning curve ❌ Rapid evolution ❌ Increasing dependency on frameworks 👉 React is powerful — but no longer beginner-friendly. 𝗛𝗼𝘄 𝘁𝗼 𝗔𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗚𝗲𝘁 𝗕𝗲𝘁𝘁𝗲𝗿 Skip endless tutorials. ✔ Build real-world projects ✔ Clone production apps ✔ Solve real problems ✔ Focus on architecture over syntax Tutorials don’t make you job-ready. Shipping projects does. 𝗙𝗶𝗻𝗮𝗹 𝗧𝗮𝗸𝗲 React in 2026 is about: → Performance → Server-first thinking → Scalable architecture → Real-world problem solving Adapt — and you stay relevant. Ignore it — and you fall behind. What’s the biggest challenge you're facing with modern React right now?
To view or add a comment, sign in
-
-
🚀 **Day 1 – #RxJS Journey** **Part 1: What is RxJS & Why in Angular?** #RxJS = **Reactive Extensions for #JavaScript** Starting the journey with one of the most powerful concepts in Angular — **#RxJS** 👉 In simple terms: RxJS helps you handle **asynchronous data, events, and streams** in a clean and scalable way. --- ### Why RxJS in Angular? ✔️ HTTP Calls → `HttpClient` returns Observables ✔️ Forms → `valueChanges` is an Observable ✔️ Routing → `ActivatedRoute.paramMap` is an Observable ✔️ State Management → NgRx is built on RxJS ✔️ Real-time UI → React instantly to user actions and data changes --- ### What is an Observable? Think of it like a Netflix subscription 📺 👉 Subscribe once → keep receiving data over time ✔️ Can emit multiple values ✔️ Can complete, error out, or keep streaming ✔️ Nothing happens until you subscribe --- ### Basic RxJS in Angular ```ts cityList: string[] = ["Pune", "Mumbai", "Nagpur"]; cittList$ = of(["Pune", "Mumbai", "Nagpur"]); cityList2$ = from(["Pune", "Mumbai", "Nagpur"]) constructor() { this.cittList$.subscribe((cityData: string[])=>{ console.log(cityData) }) this.cityList2$.subscribe((res: string)=>{ console.log(res) }) const myObs$ = new Observable(value=>{ value.next("This is Demo Text") }) } ``` --- ### Key Learnings ✔️ `of()` → emits the entire array at once ✔️ `from()` → emits one value at a time ✔️ `Observable` → create your own data stream --- **Mindset:** Consistency > Perfection Next up: RxJS Operators #RxJS #Angular #WebDevelopment #Frontend #LearnInPublic #SatendraCoder
To view or add a comment, sign in
-
-
❓ What actually happens when you call fetch('/api')? So I sat down and figured it out. Here's what blew my mind 👇 💡 The JS engine itself is TINY. Just two things inside it: 📦 Memory Heap — where your objects live 📚 Call Stack — tracks what function is running That's it. It can't do timers. It can't make network requests. It can't even listen for a click. 🤯 🎭 So who does all the async work? The BROWSER does. Not JavaScript. ⚙️ Web APIs (written in C++) handle the heavy lifting on separate threads: 🌐 fetch — network requests ⏱️ setTimeout — timers 🖥️ DOM — page manipulation 🖱️ Events — clicks, scrolls, keypresses 💾 LocalStorage, Geolocation, WebSockets… When they finish, they drop callbacks into two queues: 🟢 Microtask Queue (HIGH priority) → Promises, await, queueMicrotask 🔴 Callback Queue (LOW priority) → setTimeout, click, fetch response 🔄 Then the Event Loop steps in: 1️⃣ Is the Call Stack empty? 2️⃣ Drain ALL microtasks first 3️⃣ Run ONE macrotask 4️⃣ Let the browser paint 5️⃣ Repeat forever 🎯 This explains SO much: ✅ Why a heavy loop freezes your page (stack never empties) ✅ Why Promise.then() ALWAYS beats setTimeout(fn, 0) ✅ Why async/await isn't magic — it's just microtask syntax ✅ Why single-threaded doesn't mean single-tasking 👨🍳 My favorite mental model: The JS engine is a single chef. Web APIs are robot assistants running errands in the background. The Microtask Queue is the VIP line. The Callback Queue is the regular line. The Event Loop is the maître d' — but only seats people when the chef is free. 💥 The biggest realization: "JavaScript" the language and "JavaScript" the thing running in your browser are two VERY different things. ✨ The language is small. 🌊 The runtime around it is massive. I mapped the whole thing out with diagrams — call stack traces, V8's Ignition/TurboFan pipeline, the full click-to-fetch-to-DOM lifecycle. Dropping it in the comments 👇 👋 What's something you use every day but never really looked under the hood of? #JavaScript #WebDevelopment #Frontend #V8 #EventLoop #CodeNewbie
To view or add a comment, sign in
-
✅ JavaScript Advanced Concepts You Should Know 🔍💻 These concepts separate beginner JS from production-level code. Understanding them helps with async patterns, memory, and modular apps. 1️⃣ Closures A function that "closes over" variables from its outer scope, maintaining access even after the outer function returns. Useful for data privacy and state management. function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 2️⃣ Promises & Async/Await Promises handle async operations; async/await makes them read like sync code. Essential for APIs, timers, and non-blocking I/O. // Promise chain fetch(url).then(res => res.json()).then(data => console.log(data)).catch(err => console.error(err)); // Async/Await (cleaner) async function getData() { try { const res = await fetch(url); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 3️⃣ Hoisting Declarations (var, function) are moved to the top of their scope during compilation, but initializations stay put. let/const are block-hoisted but in a "temporal dead zone." console.log(x); // undefined (hoisted, but not initialized) var x = 5; console.log(y); // ReferenceError (temporal dead zone) let y = 10; 4️⃣ The Event Loop JS is single-threaded; the event loop processes the call stack, then microtasks (Promises), then macrotasks (setTimeout). Explains why async code doesn't block. 5️⃣ this Keyword Dynamic binding: refers to the object calling the method. Changes with call site, new, or explicit binding. const obj = { name: "Sam", greet() { console.log(`Hi, I'm ${this.name}`); }, }; obj.greet(); // "Hi, I'm Sam" // In arrow function, this is lexical const arrowGreet = () => console.log(this.name); // undefined in global 6️⃣ Spread & Rest Operators Spread (...) expands iterables; rest collects arguments into arrays. const nums = [1, 2, 3]; const more = [...nums, 4]; // [1, 2, 3, 4] function sum(...args) { return args.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 7️⃣ Destructuring Extract values from arrays/objects into variables. const person = { name: "John", age: 30 }; const { name, age } = person; // name = "John", age = 30 const arr = [1, 2, 3]; const [first, second] = arr; // first = 1, second = 2 8️⃣ Call, Apply, Bind Explicitly set 'this' context. Call/apply invoke immediately; bind returns a new function. function greet() { console.log(`Hi, I'm ${this.name}`); } greet.call({ name: "Tom" }); // "Hi, I'm Tom" const boundGreet = greet.bind({ name: "Alice" }); boundGreet(); // "Hi, I'm Alice" 9️⃣ 💡 Practice these in a Node.js REPL or browser console to see how they interact. 💬 Tap ❤️ if you're learning something new!
To view or add a comment, sign in
-
🎯 Angular Outputs – How Child Components Talk Back 🔥 Most beginners learn how to pass data into components… But the real magic? 👉 When a child component sends data back to the parent That’s where Angular Outputs come in 🚀 🔹 Think of it like this: Parent → Child = Input ✅ Child → Parent = Output 🔁 🔍 Simple Example: import { Component, output } from '@angular/core'; @Component({ selector: 'custom-slider', }) export class CustomSlider { valueChanged = output<number>(); updateValue() { this.valueChanged.emit(50); } } 👉 Parent listens like this: <custom-slider (valueChanged)="onValueChange($event)"></custom-slider> 🧠 What’s happening here? ✔ Child emits event using .emit() ✔ Parent listens using (eventName) ✔ Data is passed using $event 🔥 Real Power: You can send any data: this.valueChanged.emit(7); // number this.valueChanged.emit({ x: 100, y: 200 }); // object ⚡ Pro Tips: ✔ Output names are case-sensitive ✔ Events do NOT bubble like DOM events ✔ Use camelCase naming ✔ Avoid naming conflicts with native events 💡 Realization: “Inputs pass data down… Outputs bring data back up.” 👉 That’s how Angular components communicate like a team 🤝 🚀 Why it matters: ✔ Enables component interaction ✔ Helps build reusable UI ✔ Essential for real-world apps 📌 Bonus: Old way (still valid): @Output() valueChanged = new EventEmitter<number>(); New way (recommended): valueChanged = output<number>(); If you're preparing for Angular interviews, this is a must-know concept 🔥 #Angular #WebDevelopment #FrontendDeveloper #JavaScript #SoftwareDevelopment #CodingJourney #BuildInPublic #Developers #TechLearning
To view or add a comment, sign in
-
-
Do your Angular callbacks feel like a game of "I hope this data matches"? 🤔 Here is #Day18 of #TypescriptBeforeAngular with SANDEEP KUMAR (#IAM5K): Function Types (Defining Callbacks and Event Handlers) We define a callback function in a service, type the argument as any, and later accidentally pass the wrong data from our component. JavaScript won't stop you, so you only find out when your application crashes at runtime for the user. Today, we meet the contract of safe communication: #FunctionTypes. 1️⃣ What are Function Types? In #TypeScript, you don’t always need a formal blueprint (like an Interface or a Class) to define an object’s structure. Instead of building everything from scratch, you can use Function Types to define the specific "shape" of a function—exactly what parameters it requires (inputs) and what type it returns (output). // The recipe: Input must be string, output must be string. type GreetFunction = (name: string) => string; // Initialization: TypeScript guarantees this function matches: const greet: GreetFunction = (name) => `Hello, ${name}!`; 2️⃣ Significance in #Angular: When I first started, my app communication was a mess. Every service callback used any, leading to confusing template errors because the component was receiving data it didn't expect. In modern Angular (especially for defining @Output() properties or asynchronous Service callbacks), Function Types are essential. Whether you are: Defining an EventEmitter<(data: string) => void>. Creating a callback contract for a dynamic service method. Being explicit about your function types ensures that your component and service are perfectly aligned. The compiler guarantees that you always pass the right data, in the right format, to the right handler. It turns "I think this works" into "I know this works." It is about building a project that isn't just "typed," but truly truly safe. 💡 Beginner Tip: Think of Function Types as standardized handshake agreements. If you use them to document the expected signature of your callbacks and event handlers, your code becomes vastly easier to read and maintain, especially as your application grows and your communication logic becomes more complex. 👉 What is the most complex callback structure ((A, B, C) => void) you use in your Angular app?👇 Connect/Follow me SANDEEP KUMAR so you dont miss the next concept. #WebDev #CodingTips #NewDeveloper #CleanCode #FunctionTypes #Callbacks #Programming #TypeSafety #Javascipt #BTech
To view or add a comment, sign in
-
-
When Signals dropped in Angular, I made a classic mistake.🚦 Started swapping out RxJS in every file I touched. BehaviorSubjects, combineLatest, even some perfectly fine switchMap chains, all gone. Felt great honestly. Even had this quiet confidence that I'd finally "got" Signals, like I'd properly made the switch and left the old way behind. Fast forward two weeks. We had a real-time dashboard where multiple APIs were firing, responses coming back out of order, requests overlapping each other. Classic race condition situation. I tried solving it with Signals. Spent a good chunk of an afternoon on it. A teammate looked at my screen and just said: "why not switchMap?" One operator. Fixed in 10 minutes. I felt a little stupid ngl. That's when I realised I'd been thinking about this wrong the whole time. Signals are genuinely great but they have no concept of time. They won't cancel an in-flight request. They won't debounce a fast-typing user. They won't retry a failed call. RxJS was literally built for that world. The way I think about it now: Is the problem about what value something has? → Signal Is the problem about when or how that value gets here? → RxJS And when you need both, *toSignal()* exists for exactly that. // Signal — owns the state searchQuery =signal(''); // Bridge: Signal → Observable → switchMap → back to Signal results =toSignal(toObservable(this.searchQuery).pipe(debounceTime(300),distinctUntilChanged(),switchMap(query =>this.http.get(`/api/search?q=${query}`))),{ initialValue:[]}); Search input as a Signal, HTTP call as an Observable with switchMap, result piped back via toSignal(). Cancellation just works. No manual subscription cleanup. Honestly took me longer than I'd like to admit to stop forcing one to do the other's job. Curious, did anyone else go through this when Signals first dropped, or was it just me? 📚 Resources: → Angular Signals: angular.dev/guide/signals → RxJS interop (toSignal / toObservable): https://lnkd.in/dmqasMKn → Signals vs RxJS breakdown: https://lnkd.in/dw8CdY9R #Angular #RxJS #Signals #Frontend #WebDevelopment #AngularDeveloper #JavaScript
To view or add a comment, sign in
-
🚀 Day 22/100 – Implementing Deep Clone Function in JavaScript Today I explored how to create a deep clone function in JavaScript. Unlike shallow copy, a deep clone creates a completely independent copy of an object, including all nested objects and arrays. 🧠 Problem: Create a custom implementation of a deep clone function. ✅ Solution: function deepClone(value, weakMap = new WeakMap()) { // Handle primitives and functions if (value === null || typeof value !== "object") { return value; } // Handle circular references if (weakMap.has(value)) { return weakMap.get(value); } // Handle Date if (value instanceof Date) { return new Date(value); } // Handle RegExp if (value instanceof RegExp) { return new RegExp(value); } // Handle Array or Object const clone = Array.isArray(value) ? [] : {}; weakMap.set(value, clone); for (let key in value) { if (value.hasOwnProperty(key)) { clone[key] = deepClone(value[key], weakMap); } } return clone; } // Example const obj = { name: "Ben", address: { city: "Ghaziabad", }, }; obj.self = obj; // circular reference const cloned = deepClone(obj); console.log(cloned); console.log(cloned !== obj); // true console.log(cloned.address !== obj.address); // true ✅ Output: Deep copied object without shared references 💡 Key Learnings: • Deep clone copies nested structures completely • Handles circular references using WeakMap • Works with arrays, objects, Date, and RegExp • Prevents accidental mutation of original data 📌 Real World Usage: • State management (React / Redux) • Avoiding mutation bugs • Caching and data snapshots • Complex form handling Understanding deep cloning helps in writing predictable and bug-free applications 🔥 I’m currently open to Frontend Developer opportunities (React / Next.js) and available for immediate joining. 📩 Email: bantykumar13365@gmail.com 📱 Mobile: 7417401815 If you're hiring or know someone who is, I’d love to connect 🤝 #OpenToWork #FrontendDeveloper #JavaScript #DeepClone #ReactJS #NextJS #ImmediateJoiner #100DaysOfCode
To view or add a comment, sign in
More from this author
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