Understanding — Shallow vs Deep Copy in JavaScript Copying objects in JavaScript looks simple… but can lead to unexpected bugs if you don’t know the difference between shallow and deep copy. -> A shallow copy only copies the first level -> A deep copy creates a completely independent clone 🚨 Why this matters? If you mutate a nested object in a shallow copy, it will also affect the original object! 💡 Common ways: Shallow → {...obj}, Object.assign() Deep → structuredClone(), JSON.parse(JSON.stringify(obj)) 🧠 Key Takeaway: Always use deep copy when dealing with nested data to avoid accidental mutations. #JavaScript #FrontendDevelopment #WebDevelopment #CodingTips #CleanCode #LearnInPublic #DeveloperJourney
JavaScript Shallow vs Deep Copy: Avoid Accidental Mutations
More Relevant Posts
-
𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗚𝗲𝗺𝘀: 𝟳 𝗨𝘀𝗲𝗳𝘂𝗹 𝗙𝘂𝗻𝗰𝗍𝗶𝗼𝗻𝘀 You use JavaScript every day, but do you know all its features? Most developers use a small part of its capabilities. Here are some useful functions to simplify your code: - Object.fromEntries() transforms key-value pairs into an object - Array.prototype.flatMap() maps and flattens an array in one step - Array.prototype.at() accesses elements using positive or negative indices - Promise.allSettled() waits for all promises to settle - String.prototype.matchAll() returns all matches of a regex - Array.prototype.findLast() and findLastIndex() search arrays from the end - queueMicrotask() schedules a microtask to run after the current execution Using these functions can reduce boilerplate code, improve readability and performance, and make your code more powerful. You can level up as a JavaScript developer by exploring the language's "forgotten corners". Source: https://lnkd.in/g2XbQTm6
To view or add a comment, sign in
-
What is the difference between shallow copy and deep copy? Copying objects in JavaScript is not always what it seems. A `shallow copy` duplicates only the first level. Nested objects are still shared by reference. A `deep copy` duplicates everything recursively. Why did this happen? - The top-level object was copied - But `address` still points to the same reference To fully isolate data, a deep copy is required. Understanding this is critical when: - Managing state - Avoiding unintended mutations - Debugging shared data issues The behaviour is subtle — but the impact is everywhere. #Frontend #JavaScript #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 From Arrays to Efficiency: Mastering Set in JavaScript Today I solved the “Unique Rows in Boolean Matrix” problem using one simple yet powerful concept — Set. At first glance, the problem looks like a typical nested loop challenge. But instead of going brute force, I leveraged Set to achieve a clean and optimal solution. 💡 Key Idea: Convert each row into a string and store it in a Set to automatically handle duplicates. ✨ Why this is powerful: Eliminates duplicates in O(1) lookup time Avoids unnecessary nested loops Keeps the solution clean and readable 📊 Complexity: Time: O(n × m) Space: O(n × m) 🔥 Takeaway: Sometimes, the difference between an average solution and an optimal one is just knowing the right data structure. Today it was Set. Tomorrow, it could be something else. 💬 Curious: Where else have you used Set to simplify a problem? #JavaScript #DSA #CodingInterview #WebDevelopment #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
I’ve now wrapped up my current deep dive into JavaScript coercion, ending with one of the most misunderstood parts of the language: "==" vs "===" My biggest takeaway is that the right way to understand equality in JavaScript is not by memorising strange examples like: - 5 == "5" - false == 0 - "" == 0 - null == undefined Instead, it is by understanding the actual rules behind them. What I learned is that === and == are backed by different abstract operations in the ECMAScript spec: 1. === → IsStrictlyEqual(x, y) 2. == → IsLooselyEqual(x, y) For ===, the mental model is simple: - if the types differ, the result is false - no cross-type coercion happens But == is not just “convert both sides to numbers”. It follows a case-by-case algorithm. Depending on the values involved, JavaScript may: 1. convert strings to numbers 2. convert booleans to numbers 3. convert objects to primitives 4. apply the special null / undefined rule 5. compare BigInt and Number in a specific way That is why: - 5 == "5" is true - false == 0 is true - null == undefined is true - but null == 0 is false The best part of learning this topic is that JavaScript now feels much less random. I also feel more confident reading the ECMAScript spec now. I do not need to learn every abstract operation in depth, but I know how to navigate the spec when I want to understand why JavaScript produced a certain result. I’ve been maintaining detailed notes on everything I learned here: GitHub repo: https://lnkd.in/ephuZ-w6 #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript
To view or add a comment, sign in
-
-
🤔 Ever seen RangeError: Maximum call stack size exceeded and wondered what it actually means? It usually comes down to how the call stack works, how recursion grows it, and why every JavaScript engine has depth limits. 🧠 JavaScript interview question What is the call stack, why does recursion have depth limits, and what causes a stack overflow? ✅ Short answer The call stack is where JavaScript keeps track of active function calls. Every recursive call adds a new stack frame. If recursion goes too deep, or never stops, the stack fills up and throws a stack overflow error. 🔍 A bit more detail JavaScript runs code on a single thread and uses the call stack to manage function execution. When one function calls another, a new execution context is pushed onto the stack. When a function finishes, it is popped off and control returns to the caller. With recursion, this push process keeps happening until a base case stops it. That is why a correct base case matters so much. Without it, or with too many nested calls, you eventually hit the engine's stack limit and get: RangeError: Maximum call stack size exceeded Example with a safe base case: function factorial(n) { if (n < 0) throw new Error("Negative values are not allowed"); if (n === 0 || n === 1) return 1; // base case return n * factorial(n - 1); // recursive case } console.log(factorial(5)); // 120 This works because the recursion has a clear stopping point. Here is the kind of pattern that causes stack overflow: function endless(n) { return endless(n + 1); // no base case } ⚠️ Important clarification Infinite recursion is not the only problem. Even valid recursion can fail if the input gets deep enough, because JavaScript engines have limited stack space. That is why for very deep problems, an iterative solution is often safer than recursion. #javascript #webdevelopment #frontend #codinginterview #learninpublic
To view or add a comment, sign in
-
👉 If you're writing modern JavaScript, these 10 underrated features can instantly improve your code 👇 💡 Optional Chaining ("?.") → Stop “cannot read property of undefined” errors 💡 Nullish Coalescing ("??") → Smarter defaults (without breaking "0" or """") 💡 Array.at() → Clean way to access last elements 💡 structuredClone() → Proper deep copy (no hacks) 💡 Promise.any() → First successful API wins 💡 Object.hasOwn() → Safer property checks 💡 replaceAll() → Replace all matches without regex 💡 Top-Level Await → Cleaner async code in modules 💡 Logical Assignment ("||=", "&&=", "??=") → Write less, do more 💡 WeakMap / WeakSet → Memory-efficient data handling 🔥 These aren’t “advanced” features — They’re modern JavaScript essentials in 2026. --- 💬 Curious — Which one are you already using in production? And which one is new for you? --- #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #Coding #SoftwareEngineering #TechJobs
To view or add a comment, sign in
-
🚀 Implementing Tail-Recursive Factorial (JavaScript) (Data Structures And Algorithms) While JavaScript engines aren't guaranteed to optimize tail calls, demonstrating the pattern is still valuable. This example shows how to rewrite the factorial function in a tail-recursive style using an accumulator. The accumulator stores the intermediate result, which is then passed along with each recursive call. When the base case is reached, the accumulator contains the final result, avoiding further operations after the recursive call. #Algorithms #DataStructures #CodingInterview #ProblemSolving #professional #career #development
To view or add a comment, sign in
-
-
Something small but nice I recently came across in JavaScript 👨💻✨ : String.trimEnd(). Earlier, whenever I needed to remove only the trailing spaces from a string, I used to write a small regex for it or sometimes even used .trim(). But .trim() removes both leading and trailing spaces, which isn’t always what we want — especially when the leading indentation actually matters. For example, I used to do something like this: const message = " Action Required: Clear Cache "; // Earlier approach const cleaned = message.replace(/\s+$/, ""); It works, but the regex isn’t exactly the most readable thing 🤯. Recently I noticed there’s a much cleaner native way 👇 const message = " Action Required: Clear Cache "; const result = message.trimEnd(); Now it clearly expresses the intent: remove only the trailing whitespace while keeping the start intact ✅. Result: " Action Required: Clear Cache" Small things like this make code more readable and intentional ✨, and since it’s part of modern JavaScript (along with trimStart()), there’s no need for regex hacks anymore. Sometimes the language already has the cleaner solution, we just discover it a bit later 😄🚀 #JavaScript #CodingTips #CleanCode #WebDev #WebDevelopment
To view or add a comment, sign in
-
🧠 JavaScript Concept: Shallow Copy vs Deep Copy When copying objects in JavaScript, understanding the difference between shallow copy and deep copy is very important. 🔹 Shallow Copy Copies only the top-level properties. Nested objects are still shared by reference. Example: const copy = { ...original }; 🔹 Deep Copy Creates a completely independent copy, including all nested objects. Example: const copy = structuredClone(original); 📌 Key Difference: Shallow Copy → Shares references Deep Copy → Fully independent copy ⚠️ Important: Modifying nested data in a shallow copy will also affect the original object. 📌 Best Practice: Use shallow copy for simple objects and deep copy when working with nested data. #javascript #frontenddevelopment #reactjs #webdevelopment #coding
To view or add a comment, sign in
-
-
Most JavaScript problems aren't about writing code — they're about understanding what it's actually doing. When you're debugging something subtle or trying to reason about performance, the issue usually isn't syntax. It's what's happening under the hood. JavaScript in Depth by James Snell is built for that layer. It focuses on how JavaScript actually works: how engines execute your code, how runtimes interact with system APIs, and why certain behaviors show up in real-world applications. It's not a step-by-step guide. It's a way to build the mental model behind the language, so you can troubleshoot more effectively, revisit edge cases with confidence, and make better use of AI-generated code instead of treating it as a black box. Explore the book: https://hubs.la/Q04bjmfM0
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