😩 I changed one object... and everything else broke. Classic JavaScript moment. You think you’ve copied an object — but you’ve only cloned the surface. Here’s what happened to me recently 👇 const user = { name: "John", address: { city: "Berlin" } }; const clone = { ...user }; clone.address.city = "Paris"; console.log(user.address.city); // 😱 "Paris" Wait — what?! I just wanted a copy… not to move the entire family. 🧠 What’s going on? The spread operator { ...obj } or Object.assign() only makes a shallow copy. That means nested objects or arrays still share references with the original. So when you mutate one, the other changes too. ✅ The Fix If you need a deep copy, you have a few safe options: // 1️⃣ Simple & built-in (modern JS) const deepClone = structuredClone(user); // 2️⃣ Old-school workaround const deepClone = JSON.parse(JSON.stringify(user)); // 3️⃣ For complex cases (like Dates, Maps, etc.) import _ from "lodash"; const deepClone = _.cloneDeep(user); Now user and deepClone are fully independent. 💡 Takeaway > A shallow copy copies values. A deep copy copies the entire structure. Know which one you need — or your state bugs will come back to haunt you. 👻 🗣️ Your Turn Have you ever been burned by this shallow copy issue? What’s your go-to method for safe cloning? #JavaScript #WebDevelopment #CodingTips #FrontendDevelopment #CleanCode #ProgrammingBugs #ES6 #CodeSmarter #DevCommunity
JavaScript Shallow Copy Gotcha: How to Deep Clone
More Relevant Posts
-
🔥 JS Loops Demystified: for vs for…in vs for…of If you’ve ever wondered which loop to use in JavaScript, you’re not alone. Choosing the wrong one can cause subtle bugs! Here’s a quick guide: 1️⃣ Classic for loop – The old reliable const arr = [10, 20, 30]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } Use when you need index access, or want full control over iteration. 2️⃣ for…in loop – Iterate over keys (property names) const arr = [10, 20, 30]; for (let key in arr) { console.log(key); // 0, 1, 2 } Works on objects too. ⚠️ Can be dangerous for arrays — also loops over inherited properties. 3️⃣ for…of loop – Iterate over values const arr = [10, 20, 30]; for (let value of arr) { console.log(value); // 10, 20, 30 } Perfect for arrays, strings, maps, sets. Safe, clean, and readable. 💡 Pro tip: Use for when you need the index. Use for…of for values (most array iterations). Avoid for…in on arrays — reserve it for objects. Small choice, huge impact on readability and bug prevention. #JavaScript #CodingTips #WebDevelopment #FrontendDev #CleanCode #JSProTips #ForOfVsForIn
To view or add a comment, sign in
-
🚀 Deep Clone an Object in JavaScript (the right way!) Most of us have tried this at least once: const clone = JSON.parse(JSON.stringify(obj)); …and then realized it breaks when the object has functions, Dates, Maps, or undefined values 😬 Let’s fix that 👇 ❌ The Problem with JSON.parse(JSON.stringify()) >It’s quick, but it: >Removes functions >Converts Dates into strings >Skips undefined, Infinity, and NaN >Fails for Map, Set, or circular references ✅ Option 1: Use structuredClone() (Modern & Fast) Available in most modern browsers and Node.js (v17+). It can handle Dates, Maps, Sets, and even circular references — no errors, no data loss. const deepCopy = structuredClone(originalObject); Simple, native, and reliable 💪 ✅ Option 2: Write Your Own Recursive Deep Clone Useful for older environments or if you want to understand the logic behind cloning. 💡 Pro Tip: If you’re working with complex or nested data structures, always prefer structuredClone(). It’s the modern, built-in, and safest way to deep clone objects in JavaScript. 🔥 Found this useful? 👉 Follow me for more JavaScript deep dives made simple — one post at a time. #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #LearnJavaScript #Programming #DeveloperCommunity #WebDev #ES6 #JSDeveloper #JavaScriptTips #JavaScriptObjects #JavaScriptClone #JavaScriptCloneObject
To view or add a comment, sign in
-
Why don't we manually free() memory in JavaScript? Thank the Garbage Collector (GC). JavaScript is a garbage-collected language, meaning it automates memory management. This prevents a whole class of bugs, like memory leaks and dangling pointers, that are common in languages like C/C++. The core challenge for any GC is to determine which objects are no longer in use. The main algorithm JavaScript engines rely on is Mark-and-Sweep. Here’s a simplified view: Roots: The GC identifies a set of "root" objects that are always accessible (e.g., the global object, the current function's call stack). Mark Phase: It traverses the entire object graph starting from these roots. Every object it can reach is "marked" as in-use. Sweep Phase: The collector then scans the entire memory heap. Any object that was not marked is unreachable ("garbage") and is deallocated. Modern engines (like V8) use advanced variations like a generational collector. This optimizes the process by making an assumption: most objects "die young." It splits memory into a "New Generation" (or "Young Space") and an "Old Generation." New objects are created in the New Generation, which is scanned very frequently. Objects that survive a few collection cycles are "promoted" to the Old Generation, which is scanned less often. This "automatic" cleanup is a core feature of JS, but it's not "free"—GC pauses can impact an app's responsiveness. As developers, understanding this process helps us optimize our code to work with the GC, not against it. #JavaScript #NodeJS #WebDevelopment #MemoryManagement #GarbageCollection #MarkAndSweep #Performance #V8 #SoftwareArchitecture #CS
To view or add a comment, sign in
-
Why 0.1 + 0.2 0.3 in JavaScript: The Truth About Floating-Point Numbers Why 0.1 + 0.2 ≠ 0.3 in JavaScript If you’ve ever typed this into your console: 0.1 + 0.2 === 0.3 // false console.log(0.1 + 0.2) // 0.30000000000000004 …and felt confused, you’re not alone. This tiny difference has confused developers for years, but once you understand floating-point numbers, it all makes sense. JavaScript stores every number (except BigInt) as a 64-bit IEEE 754 floating-point value. That means numbers are represented in binary, not decimal. And here’s the problem: Some decimal numbers simply can’t be represented exactly in binary form. For example: 1/3 is an infinite repeating decimal in base 10: 0.333333... Similarly, 0.1 is an infinite repeating fraction in base 2 (binary). JavaScript can’t store infinite digits, so it rounds the value slightly. That’s why when you add 0.1 + 0.2, you get 0.30000000000000004. Every floating-point number is stored as three parts: Sign bit (positive or negative) Exponent (how large or small the number is) Mantissa (the precis https://lnkd.in/gTu_5jpP
To view or add a comment, sign in
-
🔍 𝗛𝗼𝘄 `𝗪𝗲𝗮𝗸𝗠𝗮𝗽` 𝗮𝗻𝗱 `𝗪𝗲𝗮𝗸𝗦𝗲𝘁` 𝗛𝗲𝗹𝗽 𝗣𝗿𝗲𝘃𝗲𝗻𝘁 𝗠𝗲𝗺𝗼𝗿𝘆 𝗟𝗲𝗮𝗸𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Memory leaks can sneak up on any developer—even the most vigilant. Fortunately, JavaScript’s `WeakMap` and `WeakSet` offer powerful tools to manage object lifecycles and avoid lingering references. In this article, you’ll learn: ✅ What sets `WeakMap` and `WeakSet` apart from `Map` and `Set` ✅ How these weak-referenced structures let garbage collector clean up unused objects ✅ Practical patterns: caching objects safely, managing metadata, and building memory-safe data structures 👉 𝗥𝗲𝗮𝗱 𝘁𝗵𝗲 𝗳𝘂𝗹𝗹 𝗴𝘂𝗶𝗱𝗲 𝗵𝗲𝗿𝗲: https://lnkd.in/diZEe_k9 When your app runs longer, or handles complex object graphs, these tools are game-changers. #JavaScript #WebDevelopment #MemoryManagement #Performance #WeakMap #WeakSet #CodingTips
To view or add a comment, sign in
-
💡 Shallow Copy vs Deep Copy — and a Hidden Browser API You Should Know 🚀 Ever faced this situation? You copy an object or array… and somehow, the original still changes. 😵💫 That’s the trap between shallow and deep copies in JavaScript 👇 🧩 Shallow Copy A shallow copy only duplicates the first level. Nested objects or arrays still share the same reference. 🧠 Tools that create shallow copies: Object.assign(), spread syntax (...), Array.slice() 🌊 Deep Copy A deep copy makes a completely new clone of all nested levels, so changes never affect the original. ✅ 1. Using the Modern Browser API — structuredClone() Deeply clones objects, arrays, Maps, Sets, Dates, etc... but removes methods/function it's always better to go for recursive deep copy it will take care functions. Supported in modern browsers (Chrome 98+, Node 17+) ✅ 2. Recursive Deep Copy (for custom control) #JavaScript #Frontend #WebDevelopment #CodingTips #structuredClone #DeepCopy #ShallowCopy #TechLearning
To view or add a comment, sign in
-
-
The Node.js Architecture — Event Loop, Libuv, and Thread Pool Explained At its core, Node.js runs on the V8 JavaScript engine — the same engine used in Chrome — but that’s just where it starts. The real power of Node.js lies in how it handles I/O operations (like reading files, connecting to databases, or sending network requests) without blocking the main thread. It achieves this magic using the Event Loop, powered by a C++ library called Libuv. Here’s the breakdown 👇 When you run JavaScript in Node.js, the main thread executes your code. But when your program needs to do something time-consuming — like reading a file — Node.js delegates that task to Libuv. Libuv manages a Thread Pool (usually 4 threads by default) to handle these expensive operations asynchronously. Once the work is done, the results are sent back to the Event Loop, which pushes the callback into the Callback Queue to be executed when the main thread is free. This smart design — one thread for JS execution and multiple background threads for I/O — is what makes Node.js non-blocking and highly scalable. Instead of waiting, it just moves on, letting the Event Loop coordinate all ongoing tasks efficiently. In short: 🧠 V8 executes JavaScript. ⚙️ Libuv handles async I/O operations. 🔁 Event Loop decides when callbacks run. 🧵 Thread Pool does heavy lifting behind the scenes. That’s how a single-threaded Node.js server can serve thousands of users simultaneously — not by being fast at one thing, but by never waiting for anything. ⚡ #NodeJS #WebDevelopment #Backend #MERNStack #JavaScript #EventLoop #AsyncProgramming #LearnInPublic #CodingCommunity #100DaysOfCode #DeveloperJourney
To view or add a comment, sign in
-
💛 𝗗𝗮𝘆 𝟯 — 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗻𝗱 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 Today’s focus was one of the most powerful and favorite topics in JavaScript — 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 🔁 💡 𝗖𝗼𝗻𝗰𝗲𝗽𝘁: A closure gives a function access to its outer scope even after the outer function has finished execution. This enables data encapsulation, function factories, and state preservation. 💻 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝟭 — 𝗕𝗮𝘀𝗶𝗰 𝗖𝗹𝗼𝘀𝘂𝗿𝗲: function outer() { let count = 0; return function inner() { count++; console.log("Count:", count); }; } const counter = outer(); counter(); // Count: 1 counter(); // Count: 2 🧠 Here, inner() remembers the variable count from outer() even after it’s done — that’s closure in action! 💻 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝟮 — 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗮𝗹 𝗨𝘀𝗲: Closures power concepts like private variables: function createUser(name) { return { getName: function () { return name; }, }; } const user = createUser("Ravi"); console.log(user.getName()); // Ravi 🧠 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀: ✅ Inner functions retain references to outer scope variables. ✅ Closures are the backbone of callbacks, event handlers, and functional programming. ✅ Used in frameworks like React (hooks rely on closure principles). 🔥 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Closures aren’t magic — they’re just functions remembering where they came from. #JavaScript #Closures #Functions #FrontendDevelopment #100DaysOfCode #LearningEveryday
To view or add a comment, sign in
-
🚀 5 Quick Facts About Arrays in JavaScript 1️⃣ Dynamic & Flexible – You can store numbers, strings, or even objects in the same array. 🧩 const arr = [1, "two", true]; 2️⃣ Technically Objects – typeof [] returns "object", not "array". ✅ Use Array.isArray(arr) to be sure. 3️⃣ Built for Efficiency – Use map(), filter(), and reduce() to write clean, functional code. 4️⃣ Spread Operator Power – Combine or clone arrays effortlessly. ⚙️ const merged = [...arr1, ...arr2]; 5️⃣ Zero-Indexed – The first element starts at index 0. 📍 arr[0] gives the first item. Arrays are more powerful than they look — master them, and your JS code will be cleaner, faster, and smarter 💡 #JavaScript #WebDevelopment #CodingTips #Arrays #DeveloperLife
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
lodash library can be heavy only for cloneDeep. Try punyutility. Light weight library comes with cloneDeep.