💡 Ever changed a copy of an object… and accidentally changed the original too? If you’ve worked with JavaScript, you know this painful trap all too well! Let’s clarify the difference between shallow copy and deep copy, and see how modern JS handles it. 🔹 Shallow Copy A shallow copy duplicates only the top-level properties. Nested objects or arrays are still shared. const original = { name: "Alice", details: { age: 25 } }; const shallowCopy = { ...original }; shallowCopy.details.age = 30; console.log(original.details.age); // 30 → original object changed! ✅ Top-level copied. ⚠️ Nested objects still reference the same memory. 🔹 Deep Copy A deep copy duplicates everything, including nested objects, so changes don’t affect the original. 1️⃣ Using JSON.stringify() + JSON.parse() const original = { name: "Alice", details: { age: 25 } }; const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ⚠️ Limitation: Doesn’t handle Dates, Maps, Sets, functions, or circular references. 2️⃣ Using structuredClone() (Modern JS) const original = { name: "Alice", details: { age: 25 } }; const deepCopy = structuredClone(original); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ✅ Handles most types, including Date, Map, Set, etc. ⚠️ Available in modern browsers & Node.js v17+. #JS #JavaScript #WebDevelopment #DeepCopy #ShallowCopy #CodingTips #Programming
Avoiding the Pitfall of Shallow Copy in JavaScript
More Relevant Posts
-
Why You Should Avoid Using new Number(), new String(), and new Boolean() in JavaScript In JavaScript, there is an important distinction between primitive values and object wrappers. Consider the following example: let a = 3; // primitive number let b = new Number(3); // Number object console.log(a == b); // true (type coercion) console.log(a === b); // false (different types) This inconsistency occurs because new Number(), new String(), and new Boolean() create objects, not primitive values. Although they appear similar, they can cause subtle and hard-to-detect bugs in equality checks and logical comparisons. Common Issues Confusing equality checks (== vs ===) Unintended behavior in conditionals or truthy/falsey evaluations Inconsistent data handling across the codebase Recommended Best Practices Always use literals or function calls for primitive values: // Correct usage let x = 3; let y = "Hello"; let z = true; // Safe conversions Number("3"); // → 3 (primitive) String(123); // → "123" Boolean(0); // → false Use constructors like Date, Array, Object, and Function only when you intend to create objects. For Working with Dates Instead of relying solely on the Date object, consider modern and reliable alternatives: Intl.DateTimeFormat for formatting Temporal API (in modern JavaScript runtimes) for date and time arithmetic Key Takeaway If you encounter new Number(), new String(), or new Boolean() in your codebase, it is often a sign of a potential bug. Use literals for primitives, and reserve constructors for actual objects. #JavaScript #WebDevelopment #SoftwareEngineering #ProgrammingBestPractices #CleanCode #FrontendDevelopment #NodeJS #TypeScript #Developers
To view or add a comment, sign in
-
Reflection & Object Composition in Modern JavaScript In JavaScript, objects don’t just store values — they can look at themselves and manipulate their own properties. That’s the power of Reflection. Reflection enables patterns like Object Composition, a clean, modern alternative to long prototype chains. Reflection in Action const john = { firstname: "John", lastname: "Doe" }; for (let prop in john) { if (john.hasOwnProperty(prop)) { console.log(prop + ": " + john[prop]); } } Output: firstname: John lastname: Doe Object Composition — the ES6+ Way Instead of relying on libraries like Lodash or Underscore, modern JS gives us built-ins: 1️⃣ Object.assign() Object.assign(john, { address: "123 Main St" }, { getFirstName() { return this.firstname; } }); 2️⃣ Spread Operator (ES2018) const extendedJohn = { ...john, address: "123 Main St", getFirstName() { return this.firstname; } }; Object.assign() → Mutates the object Spread { ...obj } → Creates a new one Why It Matters No external libraries needed Clean, readable syntax Full control over mutation or immutability 100% native and widely supported Takeaway: With ES6+, Object.assign() and the spread operator { ...obj } give you all the power of extend, natively — Reflection + Composition, the modern way. #JavaScript #ES6 #FrontendDevelopment #WebDevelopment #CleanCode #ProgrammingTips #React #TypeScript
To view or add a comment, sign in
-
Demystifying the Prototype in JavaScript If there’s one concept that confuses most developers (even experienced ones), it’s the Prototype. Unlike traditional class-based languages, JavaScript uses prototypal inheritance — meaning objects can inherit directly from other objects. Every JS object has a hidden reference called its prototype, and this is what makes inheritance possible. 🔹 How It Works When you access a property like obj.prop1: 1️⃣ JS first checks if prop1 exists on the object itself. 2️⃣ If not, it looks at the object’s prototype. 3️⃣ If still not found, it continues up the prototype chain until it either finds it or reaches the end. So sometimes a property seems to belong to your object — but it actually lives further down the chain! Example const person = { firstname: "Default", lastname: "Default", getFullName() { return this.firstname + " " + this.lastname; } }; const john = Object.create(person); john.firstname = "John"; john.lastname = "Doe"; console.log(john.getFullName()); // "John Doe" Here’s what happens: JS looks for getFullName on john. Doesn’t find it → checks person (its prototype). Executes the method with this referring to john. Key Takeaways The prototype is just a hidden reference to another object. Properties are looked up the prototype chain until found. The this keyword refers to the object calling the method, not the prototype. Avoid using __proto__ directly — use Object.create() or modern class syntax. One-liner: The prototype chain is how JavaScript lets one object access properties and methods of another — simple, flexible, and core to the language. If you found this helpful, follow me for more bite-sized explanations on JavaScript, React, and modern web development #JavaScript #WebDevelopment #Frontend #React #TypeScript #Coding #LearningInPublic #SoftwareEngineering #TechEducation #WebDevCommunity
To view or add a comment, sign in
-
🚀 JavaScript Tip of the Day — Currying & Function Composition Most developers know about higher-order functions… but have you explored currying yet? 😎 🧠 What is Currying? Currying transforms a function that takes multiple arguments into a sequence of functions, each taking one argument. 💻 Example: function add(a) { return function(b) { return a + b; }; } console.log(add(2)(3)); // Output: 5 ✅ This means you can reuse and partially apply functions easily. Example: const add10 = add(10); console.log(add10(5)); // 15 console.log(add10(20)); // 30 ⚡ Why use it? Enhances code reusability Makes your functions more modular & composable Great for functional programming patterns 🧩 Bonus: Function Composition Combine multiple small functions into one powerful operation: const multiply = (x) => x * 2; const square = (x) => x * x; const compose = (f, g) => (x) => f(g(x)); console.log(compose(square, multiply)(3)); // (3*2)^2 = 36 🎯 Pro Tip: Currying + Composition = Clean, predictable, and reusable code — hallmarks of a great JavaScript developer. #JavaScript #Angular #WebDevelopment #Frontend #CodingTips #FunctionalProgramming #Developers #JSInterview #MEANStack
To view or add a comment, sign in
-
🧠 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐜𝐚𝐧 𝐛𝐞 𝐰𝐞𝐢𝐫𝐝. 𝐄𝐬𝐩𝐞𝐜𝐢𝐚𝐥𝐥𝐲 𝐰𝐡𝐞𝐧 𝐢𝐭 𝐜𝐨𝐦𝐞𝐬 𝐭𝐨 𝐭𝐲𝐩𝐞 𝐜𝐨𝐞𝐫𝐜𝐢𝐨𝐧. You write a simple expression. Expect a number. Get a string. Or worse NaN. Let’s walk through 5 real examples that trip up even experienced devs and what they actually return. 👇 🔹 1 + "2" + "2" Returns: "122" Why? 1 + "2" → "12" (number + string = string) "12" + "2" → "122" 🔹 1 + +"2" + "2" Returns: "32" Why? +"2" → 2 1 + 2 → 3 3 + "2" → "32" 🔹 1 + -"1" + "2" Returns: "02" Why? -"1" → -1 1 + (-1) → 0 0 + "2" → "02" 🔹 +"1" + "1" + "2" Returns: "112" Why? +"1" → 1 1 + "1" → "11" "11" + "2" → "112" 🔹 "A" - "B" + 2 Returns: NaN Why? "A" - "B" → NaN NaN + 2 → still NaN 💡 Key takeaways: - Unary + converts strings to numbers. - Mixing strings and numbers with + leads to string concatenation. - Non-numeric strings in math return NaN. - Always check your operand types before using +, -, or ==. If you’ve ever been confused by JavaScript’s quirks, you’re not alone. Type coercion is one of the most common sources of bugs in JS. Want more no fluff JavaScript breakdowns? Follow me here 👉 Sumit Mitra JavaScript can be weird. Especially when it comes to type coercion. #JavaScript #WebDevelopment #Frontend #CodingTips #TypeCoercion #JS #SoftwareEngineering
To view or add a comment, sign in
-
JavaScript Simplified: Destructuring & Spread Operator Ever noticed how JavaScript lets you write cleaner and shorter code? That’s where Destructuring and the Spread Operator (...) come in! What is Destructuring? Destructuring means “unpacking” values from arrays or objects into variables— instead of accessing each one manually. const user = { name: "Sameer", age: 22 }; const { name, age } = user; console.log(name, age); // Sameer 22 You can even rename or set default values: const { country: location = "India" } = user; What is the Spread Operator (...)? The spread operator helps you copy, merge, or expand arrays and objects effortlessly. const fruits = ["apple", "banana"]; const moreFruits = ["orange", "grapes"]; const allFruits = [...fruits, ...moreFruits]; console.log(allFruits); // ["apple", "banana", "orange", "grapes"] It also works great with objects: const user = { name: "Sameer", age: 22 }; const updatedUser = { ...user, age: 23 }; console.log(updatedUser); // { name: "Sameer", age: 23 } In short: Destructuring → Pull out values easily Spread → Copy or merge effortlessly #JavaScript #WebDevelopment #Frontend #CodingTips #Destructuring #SpreadOperator #LearnJS
To view or add a comment, sign in
-
🚀 Day 30/50 – Function Currying in JavaScript Think of Function Currying like building a relationship. You don’t propose directly 😅 First comes the “Hi Hello 👋” phase → then friendship ☕ → and finally… the proposal ❤️ In JavaScript, instead of passing all arguments at once, Function Currying lets us pass them step by step, each step returning a new function until the final output is achieved. Here’s a simple code analogy from my video: function proposeTo(crush) { return function (timeSpent) { return function (gift) { return `Dear ${crush}, after ${timeSpent} of friendship, you accepted my ${gift}! 🥰`; }; }; } console.log(proposeTo("Sizuka")("3 months")("red rose 🌹")); Each function takes one argument and returns another function — making the code modular, flexible, and easy to reuse. 👉 This is Function Currying — one argument, one step, one perfect result. 🎥 Watch the full short video here: 🔗 https://lnkd.in/g-NkeYBc --- 💡 Takeaway: Function Currying isn’t just a JavaScript trick — it’s a powerful pattern for cleaner, more composable functions that enhance reusability and maintainability in modern frontend code. --- Would love to know: 👉 What’s your favorite JavaScript concept that clicked instantly when you saw it explained simply? #javascript #frontenddevelopment #webdevelopment #coding #programming #softwareengineering #learnjavascript #100daysofjavascript #techsharingan #developers #careergrowth
To view or add a comment, sign in
-
🔥 JavaScript: When “prototype” is NOT an object 👀 We all learn early — > “Every function in JavaScript has a prototype property that is an object.” But JavaScript loves exceptions 😏 Here are some surprising cases where prototype is not an object 👇 RegExp.prototype // → /(?:)/ Array.prototype // → [] Function.prototype // → ƒ () {} Number.prototype // → Number {} String.prototype // → String {} Boolean.prototype // → Boolean {} Symbol.prototype // → Symbol {} BigInt.prototype // → BigInt {} 💡 Notice something? Some of these are functions, arrays, or even regular expressions! That’s because their prototypes are actual instances of their types, not plain objects — so that all instances inherit their core methods directly. For example: Array.prototype.push === [].push // true ✅ RegExp.prototype.test === /abc/.test // true ✅ So next time you assume prototype is always {}, remember — JS is full of living examples 😉 --- 💬 Have you ever found a weird prototype behavior while debugging? Drop it in the comments — let’s break more JS myths together! ⚙️ #JavaScript #WebDevelopment #LearningEveryday #Frontend
To view or add a comment, sign in
-
Going back to basics 🌱 When you copy an object or array in Javascript are you really creating a new copy, or just another reference to the same memory? That’s where "Shallow Copy" and "Deep Copy" come into play. A "Shallow Copy" creates a new object, but only copies the top level properties "nested objects" or "arrays" are still linked by reference. So, if you change a nested value in the copied object,it also affects the original one. On the other hand, a "Deep Copy" creates a completely independent clone all "nested values" are copied as well. This means both the original and the copy live their own separate lives. Below I have added a simple example to show what is happening in both cases - // Shallow Copy Here, we used the "spread operator (...)" to copy the object but since it’s a shallow copy, the nested details object still points to the same reference. // Deep Copy Here, we used "JSON.parse(JSON.stringify())" to create a true clone, this process "breaks the reference", making both objects completely independent. I also got to know there are a few other ways to deep copy like using "structuredClone(obj)" a newer built in method in modern JS or "lodash.cloneDeep(obj)" for more complex structures , will read about them. #JavaScript #Frontend
To view or add a comment, sign in
-
-
Going back to basics 🌱 How Javascript executes your code inside the JS Engine ? Let’s say you have a "landing page" that needs a bit of interactivity maybe a "button click". So, you add a JavaScript file to make it all work smoothly. Now, these are are steps that will occure behind the scene - 1. The "Javascript engine" first reads your code from top to bottom, checking if there are any "syntax errors". Then it converts the code into a structured format called an "Abstract Syntax Tree (AST)" basically something the computer can understand. 2. Interpretation : This is where the Javascript engine’s interpreter (like "Ignition" in Chrome’s V8 engine) turns your code into "bytecode" for faster execution. (No need to stress about these , just know this step helps your code run faster, we will explore it more later.) 3. Optimization (JIT) : If you remember, we already discussed "Just-in-time (JIT)" Compilation in an earlier post that’s exactly what happens here. While your page is running, the Javascript engine keeps an eye on which parts of your code run frequently for example, a function that executes every time a button is clicked. When it notices such patterns, the JIT Compiler steps in and converts those parts into machine code, so the next time they run, it happens much faster. 4. Execution : Now, whenever you interact with your page like "clicking a button", the engine runs the already optimised machine code directly. That’s how things happen when you add Javascript to your page. But...but..but , if there is no Javascript file, will the JavaScript engine still work???? #Javascript #Frontend
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