💡 JavaScript Shallow Copy vs Deep Copy 1. Shallow Copy: 📌 Copies only top-level properties (primitives). 📌 Nested objects (arrays, objects) share the same reference. 🎙️ Modifying a top-level primitive in the copy does not affect the original, but modifying a nested object will affect the original, because both share the same reference. 💡 Example: const original= { a: 1, b: { c: 2 } }; const copy= { ...original }; copy.a =100; copy.b.c =200; console.log(original.a); // 1 top-level primitive unaffected console.log(original.b.c); // 200 nested object changed 2. Deep Copy: 📌 Creates a completely independent copy of the object, including all nested objects or arrays. 📌 Modifying any part of the deep copy, including deeply nested properties, has no affect on the original object ⚙️ Methods: Simple objects: JSON.parse(JSON.stringify(obj)) Complex objects: structuredClone(obj) or lodash.cloneDeep(obj) 💡 Example: const original = { name: "Vijay", hobbies: ["Acting", "Dancing"], address: { city: "Ramnad", country: "India" } }; const copy = structuredClone(original); copy.name = "Ajith"; copy.hobbies.push("Racing"); copy.address.city = "Chennai"; console.log(original); /* { name: "Vijay", hobbies: ["Acting", "Dancing"], address: { city: "Ramnad", country: "India" } } */ console.log(copy); /* { name: "Ajith", hobbies: ["Acting", "Dancing", "Racing"], address: { city: "Chennai", country: "India" } } */ #JavaScript #Coding #Programming #TechPost #ShallowCopy #DeepCopy
JavaScript Shallow vs Deep Copy: Understanding the Difference
More Relevant Posts
-
Shallow Copy vs Deep Copy in JavaScript Many developers encounter challenges with this concept early in their careers—and if misunderstood, it can lead to subtle but critical bugs in applications. What’s happening behind the scenes? In JavaScript, objects are stored in memory, and variables store references (addresses) to those objects—not the actual data itself. 🔹 Shallow Copy A shallow copy creates a new outer object, but nested objects are not duplicated. Instead, their references are shared. As a result, changes made to nested properties affect both the original and the copied object. Analogy: Two people pointing to the same house—if one makes a change, both observe it. 🔹 Deep Copy A deep copy creates a completely independent object, including all nested structures. No references are shared, so modifications remain isolated. Analogy: Building an entirely new house—changes made to one do not impact the other. ⚠️ Why does this matter in real-world applications? React state management issues Unexpected UI updates Data mutation in APIs Difficult-to-trace bugs during debugging Key Takeaway: Shallow Copy = Shared references (potential risk) Deep Copy = Independent data (safer approach) #JavaScript #ReactJS #WebDevelopment #FrontendDevelopment #SoftwareEngineering #Programming #Developers #CodingLife #Tech
To view or add a comment, sign in
-
-
Many developers struggle with unexpected bugs when working with objects in JavaScript — especially when copying data. One of the most misunderstood concepts is: Deep Copy vs Shallow Copy If not handled properly, it can lead to data mutation issues and hard-to-debug problems in real applications. In this article, I’ve broken it down in a simple and practical way: ✔ Clear definition of shallow copy and deep copy ✔ Real-world examples you can relate to ✔ Differences explained in a structured format ✔ When to use which approach ✔ Common pitfalls to avoid Whether you're a beginner or preparing for interviews, this will strengthen your fundamentals. 🔗 Read the full article: https://lnkd.in/gt9zcmkP Would love to hear your thoughts — have you faced this issue before? #JavaScript #Programming #WebDevelopment #Frontend #SoftwareDevelopment #Coding #Developers
To view or add a comment, sign in
-
Shallow Copy vs Deep Copy in JavaScript Many developers struggle with this concept early in their careers and honestly, it’s one of those things that can silently break your application if not understood properly. What’s really happening behind the scenes? In JavaScript, objects are stored in memory, and variables don’t hold the actual object they hold a reference (address) to that object. 🔹 Shallow Copy Creates a new outer object But nested objects are NOT copied Instead, their reference is shared That’s why modifying nested data affects both Think of it like: Two people pointing to the same house if one changes it, both see the change. 🔹 Deep Copy Creates a completely new object Nested objects are also duplicated No shared references Changes remain isolated Think of it like: Building an entirely new house changes don’t affect the original. ⚠️ Why does this matter in real projects? React state bugs Unexpected UI updates Data mutation issues in APIs Debugging nightmares Final Takeaway: Shallow Copy = Shared References (Risky) Deep Copy = Independent Data (Safe) Have you ever faced a bug because of shallow copy? Let’s discuss #JavaScript #ReactJS #WebDevelopment #Frontend #Programming #SoftwareEngineering #CodingLife #Developers #LearnToCode #Tech
To view or add a comment, sign in
-
-
📰 A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction <p>In this tutorial, we build a complete and practical Crawl4AI workflow and explore how modern web crawling goes far beyond simply downloading page HTML. We set up the full environment, configure browser behavior, and work through essential capabilities such as basic crawling, markdown generation, structured CSS-based extraction, JavaScript execution, session handling, screenshots, link analysis, concurrent […]</p> <p>The post <a href="https://lnkd.in/dJ_YVqjF">A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction</a> appeared first on <a href="https://lnkd.in/dAdcKkWg">MarkTechPost</a>.</p> 🔗 https://lnkd.in/dJ_YVqjF #أخبار_التقنية #ذكاء_اصطناعي #تكنولوجيا
To view or add a comment, sign in
-
🚀 JavaScript Deep Dive: this – Samajh aa gaya toh game change Most devs bolte hain “haan haan this aata hai” But interview mein ya real project mein wahi pe phas jaate hain 😅 Sach simple hai: 👉 this depends on how function is called, not where it is written. 🔹 1. Global Context console.log(this); Browser → window Node → {} 👉 Environment pe depend karta hai 🔹 2. Simple Function function show() { console.log(this); } show(); Non-strict → window Strict mode → undefined 👉 Interview mein yeh twist pakka aata hai 🔹 3. Object Method const user = { name: "Sachin", greet() { console.log(this.name); } }; user.greet(); 👉 Rule yaad rakho: "Dot ke left wala hi this hota hai" 🔹 4. Arrow Function (Most Confusing 🔥) const user = { name: "Sachin", greet: () => { console.log(this.name); } }; user.greet(); 👉 Output: undefined Kyuki: Arrow function ka apna this hota hi nahi hai 👉 Wo outer scope se le leta hai 🔹 5. call / apply / bind function greet() { console.log(`Hello ${this.name}`); } const user = { name: "Sachin" }; greet.call(user); greet.apply(user); const fn = greet.bind(user); fn(); 👉 Matlab tum manually control kar sakte ho this 🔹 6. Real Problem (Production Bug 💀) const user = { name: "Sachin", greet() { setTimeout(function () { console.log(this.name); }, 1000); } }; user.greet(); 👉 Output: undefined ✅ Fix setTimeout(() => { console.log(this.name); }, 1000); 👉 Arrow function saved the day 💡 Senior Insight (Yeh yaad rakho bas) 👉 this ≠ where function is written 👉 this = how function is called Agar yeh clear hai, toh 80% confusion khatam 🎯 Real-world Advice Arrow function → jab context inherit karna ho Normal function → jab dynamic this chahiye bind → callbacks mein use karo React mein galat this = hidden bugs 😅 Agar tum this confidently explain kar sakte ho, 👉 Interviewer ko instantly samajh aa jaata hai ki banda JS deep level pe samajhta hai #JavaScript #Frontend #WebDevelopment #IndianDevelopers #InterviewPrep #ReactJS #SeniorDevelopers
To view or add a comment, sign in
-
-
JavaScript is evolving quietly… and it’s actually getting better. While most of us are busy debating frameworks and AI tools, JavaScript itself has been shipping some seriously practical features lately. Here are a few that stood out to me: ✨ Iterator helpers (lazy evaluation) Chain operations like .map() and .filter() directly on iterators without creating intermediate arrays → better performance and memory usage ✨ Built-in Set operations Union, intersection, difference — things we used to write utility functions for are now native ✨ groupBy() (finally! 🙌) Grouping data is now much cleaner and more readable without custom reduce logic: Object.groupBy(users, user => user.role) ✨ Temporal API (fixing dates for real this time) A more reliable and predictable replacement for the current Date API 💡 My takeaway: We often look for new tools to improve productivity, but sometimes the language itself evolves to remove years of boilerplate. Curious — Which JavaScript feature have you started using recently that made your life easier? More info in this blog: https://lnkd.in/gFi8VyES #JavaScript #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
🚀 Add Two Numbers WITHOUT Using + in JavaScript 😳 Here’s a classic trick that interviewers LOVE 👇 Instead of using +, we use bitwise operators: 👉 XOR (^) → gives sum without carry 👉 AND (&) → gives carry 👉 << 1 → shifts carry to correct position 💡 Logic: Keep adding the partial sum and carry until carry becomes 0 Why this matters? Because this is exactly how computers perform addition internally at the binary level. 🧠 It’s not just a trick — it’s understanding how systems really work. 🔥 Example: 5 (0101) + 3 (0011) → Result = 8 (1000) 🎯 Where this helps: ✔️ Coding interviews ✔️ Bit manipulation problems ✔️ Deep understanding of low-level operations ✅ Using Bitwise Operators: function sum(a, b) { while (b !== 0) { let carry = a & b; // common bits (carry) a = a ^ b; // sum without carry b = carry << 1; // shift carry } return a; } 🔢 Example: sum(5, 3) First convert numbers to binary: 5 = 0101 3 = 0011 🧠 Core Idea This function mimics how addition works at the bit level: XOR (^) → adds bits without carry AND (&) → finds the carry << 1 → moves carry to the next position 🔁 Step-by-Step Execution 👉 Iteration 1 a = 0101 (5) b = 0011 (3) Step 1: carry carry = a & b = 0101 & 0011 = 0001 Step 2: sum without carry a = a ^ b = 0101 ^ 0011 = 0110 (6) Step 3: shift carry b = carry << 1 = 0001 << 1 = 0010 (2) 👉 Iteration 2 a = 0110 (6) b = 0010 (2) Step 1: carry carry = 0110 & 0010 = 0010 Step 2: sum without carry a = 0110 ^ 0010 = 0100 (4) Step 3: shift carry b = 0010 << 1 = 0100 (4) 👉 Iteration 3 a = 0100 (4) b = 0100 (4) Step 1: carry carry = 0100 & 0100 = 0100 Step 2: sum without carry a = 0100 ^ 0100 = 0000 (0) Step 3: shift carry b = 0100 << 1 = 1000 (8) 👉 Iteration 4 a = 0000 (0) b = 1000 (8) Step 1: carry carry = 0000 & 1000 = 0000 Step 2: sum without carry a = 0000 ^ 1000 = 1000 (8) Step 3: shift carry b = 0000 << 1 = 0000 ✅ Loop Ends Now b = 0, so loop stops. 👉 Final Answer: a = 1000 (8) 🎯 Final Understanding (Important for Interviews) We keep adding partial sum (a ^ b) And carry separately ((a & b) << 1) Repeat until no carry left 🔥 One-Line Intuition 👉 “This is binary addition where we separate sum and carry, then combine them until carry becomes zero.” Follow for more real-world coding insights 🚀 #javascript #coding #webdevelopment #programming #100daysofcode #developer #tech #interviewprep #bitwise #learncoding #dsa #ai
To view or add a comment, sign in
-
-
Latest JavaScript Updates You Should Know in 2026 JavaScript continues to evolve every year, becoming more powerful, cleaner, and developer-friendly. The latest ECMAScript updates focus less on “new syntax hype” and more on solving real-world problems developers face daily. Here are some of the most exciting recent updates: * Temporal API (Better Date Handling) Finally, a modern replacement for the confusing Date object—making time zones, parsing, and formatting much easier. (W3Schools) * Array by Copy Methods Methods like toSorted(), toReversed(), and toSpliced() allow immutable operations—perfect for React state management. (Progosling) * New Set Operations Built-in methods like union, intersection, and difference simplify complex data handling without extra libraries. (Progosling) * Iterator Helpers Functions like .map(), .filter(), .take() directly on iterators enable more efficient, lazy data processing. (Frontend Masters) * Explicit Resource Management Using using and await using helps manage resources automatically—cleaner and safer code. (W3Schools) * RegExp.escape() & Improved Error Handling Safer regex creation and better error detection improve reliability in production apps. (Progosling) * Array.fromAsync() & Async Improvements Handling asynchronous data collections is now simpler and more intuitive. (W3Schools) # The direction is clear: JavaScript is becoming more predictable, maintainable, and developer-centric, reducing the need for external utilities and boilerplate code.
To view or add a comment, sign in
-
𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝗻 𝟮𝟬𝟮𝟲 JavaScript changes. AI tools and new runtimes move fast. Many developers still make the same mistakes. Here are five traps to avoid. - Top level await It looks clean. But it causes problems in libraries. It creates race conditions. It increases bundle size. Fix: Use a singleton pattern. Wrap your connection in an async function. - The == operator Avoid ==. It uses complex logic. It breaks type safety. Fix: Use ===. Convert values to strings or numbers first. - Let in async loops Async loops with let often fail. They capture the live value. You get the same number every time. Fix: Use a const inside the loop. This captures the current value. - The this keyword Arrow functions do not bind this. They inherit from the outer scope. This leads to undefined. Fix: Use regular functions for methods. - JSON and dates JSON.parse does not create Date objects. It keeps them as strings. Calling date methods fails. Fix: Use a reviver function. Source: https://lnkd.in/g4yDDjNe
To view or add a comment, sign in
-
JavaScript is the only language where "5" + 3 is "53" but "5" - 3 is 2. Welcome to the wild world of AI Code Review! 🎢💻 In the next session of my AI Code Review series, I moved into the JS/TS ecosystem. Evaluating AI-generated JavaScript is like walking through a minefield of implicit coercion and async pitfalls. If you trust the first thing the model gives you, you're likely shipping a "silent fail." Here are the 3 biggest patterns that trip up LLMs in JavaScript: 1️⃣ The "Async Amnesia" Bug ⏳ I reviewed several functions where the AI used async/await for a fetch call, but then tried to access response.json() without awaiting it. The result? A dangling Promise instead of data. In JS, if you forget the await on that second Promise, your code doesn't wait—it just returns undefined or crashes when you try to access a property on a Promise. 2️⃣ The "Default Sort" Disaster 🔢 This is a classic. Many models will write myArray.sort() and call it a day. But in JavaScript, .sort() treats everything as a string by default. This means [1, 2, 10] becomes [1, 10, 2]. Without the explicit comparator (a, b) => a - b, your production data will look fine for small numbers but break the moment you hit double digits. 3️⃣ TypeScript "Optional" Overload 🛡️ When designing API responses, AI often defaults to one big Interface with optional fields like data? and error?. A Better Way: Use Discriminated Unions. By using a status: 'success' | 'error' discriminant, we can make invalid states (like having both data AND an error message) unrepresentable. It forces the developer to handle the data safely via type narrowing. 🚦 My JS/TS Evaluation Checklist: Promises: Is every single Promise-returning call actually await-ed? ⚡ Equality: Are we using === to avoid the "Loose Equality" coercion trap? 🕳️ Typing: Are we using discriminated unions to enforce logic at the type level? 🎯 The Takeaway: Reviewing JavaScript isn't just about finding bugs—it's about understanding the execution model (the Event Loop) well enough to know why the AI's "happy path" code will fail under pressure. What's the weirdest JS coercion or async race condition you've ever had to debug? Let’s swap stories in the comments! ⬇️ #JavaScript #TypeScript #AICodeReview #SoftwareEngineering #WebDevelopment #FrontendEngineering #FullStack #SoftwareQuality #CodingLife #TypeScriptTips IntelliForge Learning
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