👯♂️ "I changed the copy, why did the original update too?!" 😱 If you’ve ever screamed this at your monitor, you’ve fallen into the Shallow Copy Trap. 🪤 In JavaScript, objects and arrays are reference types. When you copy them, it matters how you do it. 1️⃣ The Shallow Copy (The "Surface" Clone) Methods like the spread operator [...] or Object.assign() only copy the first layer of data. - If your object has nested objects inside (like user.address.city), the copy points to the same memory location as the original. - Result: You change the copy's address, and the original user's address changes too. Bugs everywhere. 🐛 2️⃣ The Deep Copy (The "True" Clone) This creates a completely independent duplicate, including all nested levels. - The Old Way: JSON.parse(JSON.stringify(obj)) (Hack, but works for simple data). - The Modern Way: structuredClone(obj) (Native, fast, and handles dates/maps correctly). 🚀 Next time you are updating state in React or manipulating complex data, ask yourself: Do I need a clone, or do I need a twin? What is your go-to method for deep cloning these days? structuredClone or Lodash? 👇 #JavaScript #WebDevelopment #CodingTips #Frontend #ReactJS #SoftwareEngineering #Programming
Shallow Copy Trap: Avoid Bugs with Deep Clone
More Relevant Posts
-
Stop misusing JavaScript array methods. Small choices like this quietly shape code quality. One of the most common clean-code mistakes I see is using `forEach()` when the real intention is transformation. If your goal is to create a new array from existing data, `map()` is the right tool. `map()` returns a new array. It keeps your logic functional and predictable. It communicates intent clearly: “I am transforming data.” That clarity improves readability and long-term maintainability. `forEach()`, on the other hand, is built for side effects—logging, DOM updates, triggering external behavior. It does not return a new array. When you push into another array inside `forEach()`, you’re working against the language instead of with it. A simple rule of thumb: * If you’re creating a new array → use `map()` * If you’re performing side effects → use `forEach()` * If you’re filtering → use `filter()` instead of manual conditions Clean code isn’t about writing more lines. It’s about choosing the right abstraction for the job. Intentional developers let method names express meaning. So be honest—are you team `map()`, or still reaching for `forEach()` when transforming data? #JavaScript #CleanCode #FrontendDevelopment #WebEngineering #SoftwareCraftsmanship #CodeQuality #ReactJS
To view or add a comment, sign in
-
-
Day 67 of me reading random and basic but important dev topicsss..... Today I read about the Advanced JavaScript Range Properties & Methods..... Yesterday, I looked at the fundamentals of creating a Range in the DOM. Today, I explored the properties and convenience methods that make traversing and building these ranges highly efficient. When integrating raw DOM logic into frameworks like React, knowing these native shortcuts saves us from writing manual, bug-prone offset calculations. Core Range Properties: When we inspect a Range object, it gives us crucial contextual data: * startContainer / startOffset: The exact node and position where the range begins. * endContainer / endOffset: The node and position where the range ends. * collapsed: A boolean. true if the start and end are at the exact same point (think of a blinking text cursor with no characters highlighted). * commonAncestorContainer: The deepest parent element that fully wraps the entire range. (Incredibly useful for validating if a user's selection is contained within a specific UI component!). Pro Methods (Skip the math!): Instead of calculating exact indexes with setStart and setEnd, you can leverage semantic methods: * setStartBefore(node) / setStartAfter(node): Drops the boundary right outside a target node. * selectNode(node): Creates a range that encompasses the entire node, including its outer HTML tags. * selectNodeContents(node): Selects only the inside of the node......perfect for instantly capturing all the text inside a <div> or <p>. * collapse(toStart): Instantly shrinks the range to just its starting or ending cursor point. Keep Learning!!!!!! #JavaScript #WebDevelopment #DOM #FrontendDev
To view or add a comment, sign in
-
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟵 Have you ever updated one variable… and another one changed automatically? 𝙋𝙖𝙪𝙨𝙚 𝙛𝙤𝙧 𝙖 𝙨𝙚𝙘𝙤𝙣𝙙 — 𝙬𝙤𝙪𝙡𝙙 𝙮𝙤𝙪 𝙚𝙭𝙥𝙚𝙘𝙩 𝙩𝙝𝙞𝙨 𝙘𝙤𝙙𝙚 𝙩𝙤 𝙢𝙪𝙩𝙖𝙩𝙚 𝙗𝙤𝙩𝙝 𝙫𝙖𝙡𝙪𝙚𝙨? { 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟷 = { 𝚗𝚊𝚖𝚎: "𝙰𝚕𝚎𝚡" }; 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟸 = 𝚞𝚜𝚎𝚛𝟷; 𝚞𝚜𝚎𝚛𝟸.𝚗𝚊𝚖𝚎 = "𝙹𝚘𝚑𝚗"; 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚞𝚜𝚎𝚛𝟷.𝚗𝚊𝚖𝚎); // "𝙹𝚘𝚑𝚗" } Why did user1 change? Because: • Both variables point to the same memory address • No copy was created • Only the reference was shared 𝘛𝘩𝘪𝘴 𝘪𝘴 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵’𝘴 𝘝𝘢𝘭𝘶𝘦 𝘷𝘴 𝘙𝘦𝘧𝘦𝘳𝘦𝘯𝘤𝘦 𝘣𝘦𝘩𝘢𝘷𝘪𝘰𝘳 — 𝘢𝘯𝘥 𝘪𝘵’𝘴 𝘥𝘦𝘦𝘱𝘭𝘺 𝘵𝘪𝘦𝘥 𝘵𝘰 𝘮𝘦𝘮𝘰𝘳𝘺. 𝙏𝙝𝙚 𝙈𝙚𝙣𝙩𝙖𝙡 𝙈𝙤𝙙𝙚𝙡 (𝙈𝙚𝙢𝙤𝙧𝙮 𝙁𝙞𝙧𝙨𝙩) JavaScript mainly uses two memory areas: -> Stack Memory • Stores primitive values • Fixed size • Fast access -> Heap Memory • Stores objects, arrays, functions • Dynamic size • Accessed via references 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙫𝙖𝙡𝙪𝙚: A copy of the actual value is passed. Primitives (number, string, boolean, null, undefined, symbol) are always passed by value. 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙧𝙚𝙛𝙚𝙧𝙚𝙣𝙘𝙚: A memory address (reference) is passed, not the object itself. Objects & arrays live in heap memory. #JavaScript #JSFundamentals #MemoryManagement #FrontendDevelopment #ReactJS #BugFixing #InterviewPrep #LearningInPublic
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
-
-
💡 The Call Stack tracks execution. ❓ What causes a stack overflow error? The call stack is like a to-do list for JavaScript. Every time a function runs, it gets added (pushed) to the stack. When it finishes, it gets removed (popped). 👉 A stack overflow error happens when too many functions are added to the stack and it runs out of space. 🔹 Most Common Cause: Infinite Recursion function loop() { loop(); // calling itself forever } loop(); // ❌ Maximum call stack size exceeded Here, loop() keeps calling itself without stopping. Each call adds a new frame to the stack, and eventually the stack becomes full. 🔹 Proper Recursion (with base case) function countDown(n) { if (n === 0) return; // base case countDown(n - 1); } countDown(5); // ✅ works fine The base case stops the recursion and prevents overflow. ⚠️ Other Causes Deep nested function calls Large recursive algorithms without limits Circular function calls 💡 Takeaway A stack overflow happens when functions keep stacking up without finishing. Always make sure recursive functions have a clear stopping condition. #learnwithisnaan #JavaScriptTips #ModernJavaScript #ES6 #DeveloperTips #CleanCode #JSDevelopers
To view or add a comment, sign in
-
-
Reversing a string in JavaScript can be done in more than one way. I revisited this problem today and tried three approaches, each with a different mindset: // 1. Using built-in methods const reverse1 = (str) => str.split("").reverse().join(""); // 2. Using a loop (more control) function reverse2(str) { let result = ""; for (let i = str.length - 1; i >= 0; i--) { result += str[i]; } return result; } // 3. Using reduce (functional style) const reverse3 = (str) => str.split("").reduce((acc, char) => char + acc, ""); console.log(reverse1("hello")); //"olleh" console.log(reverse2("hello")); //"olleh" console.log(reverse3("hello")); //"olleh" Methods I used: • Built-in methods → concise and readable • Loop → full control and clarity • reduce → functional and expressive This reminded me that in real projects, how you think about a problem matters as much as the answer itself. Still learning, still building, still showing up. #JavaScript #FrontendDevelopment #LearningInPublic #JuniorDeveloper
To view or add a comment, sign in
-
🚀 JavaScript Tip: Say Goodbye to "Try-Catch Hell" in 2026! If your code looks like a nested pyramid of try-catch blocks just to handle a simple API call, you’re doing it the old way. The Safe Assignment Operator (?=) is officially changing how we handle errors. It treats errors as data, not as exceptions that crash your flow. ❌ THE OLD WAY (Messy & Nested): let user; try { const response = await fetch("https://lnkd.in/gEfuSwaq"); user = await response.json(); } catch (error) { console.error("Failed to fetch user:", error); } ✅ THE 2026 WAY (Clean & Linear): const [error, user] ?= await fetch("https://lnkd.in/gEfuSwaq").then(res => res.json()); if (error) return console.error("Failed:", error); console.log(user); Why developers are switching: • No more deep nesting or "let" variables defined outside blocks. • Logic remains top-to-bottom and easy to read. • It feels like Go or Rust, bringing "Error as Value" to the JS ecosystem. Are you still using traditional try-catch for everything, or have you moved to safe assignments yet? Let’s discuss in the comments! 👇 #JavaScript #WebDev #Coding #SoftwareEngineering #CleanCode #Programming #ReactJS #TechTrends
To view or add a comment, sign in
-
-
The Journey of an Embedded Object in JavaScript (Recursion in Action) Today I explored a simple but powerful concept in JavaScript: traversing nested objects using recursion. When working with deeply embedded objects (like API responses or application state), it’s important to understand how to navigate through multiple levels dynamically. 💡 What’s happening? We loop through each key in the object. If the value is another object → we call the function again (recursion). If it’s a primitive value → we print it. This is a Depth-First Search (DFS) approach applied to objects. This concept is extremely useful for: Parsing JSON responses Building form validators State inspection (NgRx / Redux) Creating flatten utilities Deep comparison algorithms 📂 I’ve added more JavaScript pattern exercises in this repository: 👉 https://lnkd.in/ej4fNeZs I’m currently strengthening my fundamentals in JavaScript, recursion, and problem-solving patterns. If you're also sharpening your JS skills, let’s connect and grow together 💪 #JavaScript #Recursion #WebDevelopment #Frontend #ProblemSolving #LearningInPublic
To view or add a comment, sign in
-
-
⭕ Mastering JavaScript Array Methods with Practical Examples Understanding array methods like map(), filter(), reduce(), and find() is essential for writing clean and efficient JavaScript code. 🔹 1. map() – Transform Data const prices = [100, 200, 300]; const updatedPrices = prices.map(price => price + 50); console.log(updatedPrices); // [150, 250, 350] Used to transform each element and return a new array. ➖ ➖➖➖➖➖➖➖➖➖➖➖➖➖ 🔹 2. filter() – Select Data const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // [2, 4, 6] Used to return elements that match a condition. ➖ ➖➖➖➖➖➖➖➖➖➖➖➖➖ 🔹 3. reduce() – Accumulate Data const cart = [500, 1000, 1500]; const totalAmount = cart.reduce((total, item) => total + item, 0); console.log(totalAmount); // 3000 Used for totals, sums, and complex calculations. ➖➖➖➖➖➖➖➖➖➖➖➖➖ 🔹 4. find() – Find First Match const users = [ { id: 1, name: "Rahul" }, { id: 2, name: "Aman" } ]; const user = users.find(userObj => userObj.id === 2); console.log(user); // { id: 2, name: "Aman" } Used to retrieve a specific item based on a condition. ✨ Strong fundamentals in JavaScript improve React components, backend logic in Node.js, and overall project performance. Continuous learning + practical implementation = Better development skills. #JavaScript #MERN #WebDevelopment #FrontendDevelopment #NodeJS #Coding #Developers
To view or add a comment, sign in
-
🚀 Day 26/30 – Flatten a Multi-Dimensional Array (Depth Controlled) 🧠 📌 Problem Given: A multi-dimensional array arr An integer depth n Return a flattened version of arr. Rules: The array may contain integers or nested arrays Only flatten elements if current depth < n Depth of first-level elements = 0 Do NOT use Array.flat() 🧠 Example 1 arr = [1, [2, [3, 4]], 5] n = 1 Output: [1, 2, [3, 4], 5] 🧠 Example 2 arr = [1, [2, [3, 4]], 5] n = 2 Output: [1, 2, 3, 4, 5] 💡 JavaScript Solution (Recursive Approach) var flat = function(arr, n) { const result = []; function flatten(current, depth) { for (let item of current) { if (Array.isArray(item) && depth < n) { flatten(item, depth + 1); } else { result.push(item); } } } flatten(arr, 0); return result; }; 🔎 Why This Works We track depth Only flatten when depth < n Recursion handles unlimited nesting Preserves element order Time Complexity: O(total elements) Space Complexity: O(total elements + recursion stack) 🧠 What This Teaches ✅ Recursion fundamentals ✅ Depth tracking ✅ Tree-like traversal ✅ Controlling execution scope ✅ How Array.flat() actually works internally ⚡ Real-World Use Cases Normalizing API responses Parsing nested JSON Flattening comment threads Handling deeply nested UI state Transforming hierarchical data #JavaScript #30DaysOfJavaScript #CodingChallenge #Recursion #DataStructures #Algorithms #FrontendDevelopment #WebDevelopment #LearnToCode #SoftwareEngineering #ProblemSolving #TechCommunity #InterviewPrep #100DaysOfCode #JSDeveloper JavaScript flatten array without flat Recursive array flattening JS Flatten array with depth JavaScript Implement Array.flat manually JavaScript recursion interview question Multi-dimensional array flatten JS Depth controlled flattening JavaScript Advanced JavaScript problem solving
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