Ever changed a variable in JavaScript only to realize you accidentally broke the original data too? 🤦♂️ That’s the classic Shallow vs. Deep Copy trap. Here is the "too long; didn't read" version: 1. Shallow Copy (The Surface Level) When you use the spread operator [...arr] or {...obj}, you’re only copying the top layer. The catch: If there are objects or arrays inside that object, they are still linked to the original. Use it for: Simple, flat data. 2. Deep Copy (The Full Clone) This creates a 100% independent copy of everything, no matter how deep the nesting goes. The easy way: const copy = structuredClone(original); The old way: JSON.parse(JSON.stringify(obj)); (Works, but it’s buggy with dates and functions). The Rule of Thumb: If your object has "layers" (objects inside objects), go with a Deep Copy. If it’s just a basic list or object, a Shallow Copy is faster and cleaner. Keep your data immutable and your hair un-pulled. ✌️ #Javascript #WebDev #Coding #ProgrammingTips
Shallow vs Deep Copy in JavaScript
More Relevant Posts
-
I recently implemented my first Linked List from scratch in JavaScript — no libraries, just raw pointer manipulation. This wasn’t just about writing code; it forced me to understand how data structures actually work under the hood. Here’s what I built: A custom Node structure with value and next pointers Core operations: addAtHead addAtTail addAtIndex deleteAtIndex get What made this interesting wasn’t the syntax — it was the edge cases and pointer management: Handling insertions at head vs tail Maintaining consistent length Avoiding broken references during insertion/deletion Fixing off-by-one errors in traversal Biggest takeaway: Linked Lists are simple in theory, but brutally unforgiving if your pointer logic is even slightly off. This exercise sharpened how I think about: Data structure integrity Boundary conditions Writing predictable, bug-resistant logic Still refining and testing edge cases — but this was a solid step forward. #JavaScript #DataStructures #LinkedList #Coding #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
-
Here are your 37 topics organized by section: Execution, Scope & Memory 1. Execution context & call stack 2. var, let, const (scope + hoisting + TDZ) 3. Lexical scope & scope chain 4. Closures (behavior, not definition) 5. Shadowing & illegal shadowing 6. Garbage collection basics & memory leaks Functions & this 7. Function declarations vs expressions 8. this binding rules (default, implicit, explicit, new) 9. call, apply, bind 10. Arrow functions vs normal functions 11. Currying & partial application 12. Higher-order functions Async JavaScript 13. Event loop (call stack, microtasks, task queue) 14. Promises & chaining 15. async / await (error handling & sequencing) 16. Race conditions & stale closures 17. Timers (setTimeout, setInterval) vs microtasks 18. Promise utilities (all, allSettled, race, any) Data, References & ES6+ 19. == vs ===, truthy / falsy & type coercion deep dive 20. Object & array reference behavior 21. Deep vs shallow copy 22. Destructuring, rest & spread 23. Map, Set, WeakMap, WeakSet Prototypes & OOP 24. Prototype chain & Object.create() 25. class syntax vs prototype under the hood 26. Inheritance patterns Error Handling 27. try/catch with async/await edge cases 28. Custom error types 29. Unhandled promise rejections Modules 30. ES Modules (import/export) vs CommonJS (require) 31. Tree shaking concept 32. Dynamic imports — import() Iterators & Generators 33. Symbol.iterator & iterable protocol 34. Generator functions (function*) 35. Connecting generators to RxJS mental model Browser & Runtime Fundamentals 36. Event bubbling, capturing, delegation, preventDefault vs stopPropagation 37. DOM vs Virtual DOM, Reflow vs repaint, Web storage, Polyfills #angular #javascript #html #css #webdeveloper #angularDeveloper
To view or add a comment, sign in
-
Three dots that changed JavaScript: ... The spread operator in action: Arrays: // Copy const copy = [...original] // Merge const all = [...arr1, ...arr2] // Add items const updated = [...items, newItem] Objects: // Copy const clone = { ...user } // Merge const combined = { ...defaults, ...config } // Update const modified = { ...user, age: 30 } Function calls: Math.max(...numbers) fetch(url, { ...defaultOptions, ...customOptions }) Before spread operator: const copy = original.slice() const merged = Object.assign({}, obj1, obj2) fn.apply(null, args) After spread operator: const copy = [...original] const merged = { ...obj1, ...obj2 } fn(...args) The magic: → No mutation (safer code) → Cleaner syntax → Works with any iterable → Essential for React state → Makes immutability easy Three dots. Infinite possibilities.
To view or add a comment, sign in
-
Difference between fundamental data structures used in JavaScript: - If you need to access items by index, you should probably be using an Array. - If you need to access items by key, you should probably be using an Object. - If you need to access items by value, you should probably be using a Map. - If you need to store unique items and perform operations on that collection, you should probably be using a Set. #javascript #concepts #developer #coding #engineer
To view or add a comment, sign in
-
Pure functions improve testability and composability. ────────────────────────────── JSON.parse and JSON.stringify Pure functions improve testability and composability. #javascript #json #serialization #data ────────────────────────────── Key Rules • Avoid mutating shared objects inside utility functions. • Write small focused functions with clear input-output behavior. • Use const by default and let when reassignment is needed. 💡 Try This const nums = [1, 2, 3, 4]; const evens = nums.filter((n) => n % 2 === 0); console.log(evens); ❓ Quick Quiz Q: What is the practical difference between let and const? A: Both are block-scoped; const prevents reassignment of the binding. 🔑 Key Takeaway Modern JavaScript is clearer and safer with immutable-first patterns. ────────────────────────────── Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery.
To view or add a comment, sign in
-
Most developers only learn this for exams… not for real systems 👇 ER Model ≠ Relational Model ER Model → conceptual view of data (entities, relationships, attributes) 🧠 Relational Model → actual implementation in tables (rows, columns, keys) 🗄️ When building real systems, you don’t just design ER diagrams — you translate them into relational schemas using rules like: strong entities → tables, weak entities → composite keys, multivalued attributes → separate tables, and relationships → foreign keys. This is where many devs struggle ⚠️ because a good schema isn’t just “converted” — it’s designed for consistency, scalability, and query performance. This small distinction changes how you design systems. Building systems > memorizing concepts 🚀 What’s one concept developers often misunderstand? 🤔 #fullstackdeveloper #softwareengineering #webdevelopment #javascript #reactjs #backend #buildinpublic
To view or add a comment, sign in
-
-
If you're still using JSON.stringify(a) === JSON.stringify(b) for deep comparisons, you're leaving performance on the table. It works - until it doesn't. Key ordering differences, undefined values, and circular references will silently break your logic in production. Here are real alternatives worth benchmarking: - structuredClone + manual check: fast for simple objects - Lodash isEqual: reliable, handles edge cases, battle-tested - fast-deep-equal: consistently wins benchmarks for plain objects A quick real-world example: import isEqual from 'fast-deep-equal'; const prev = { user: { id: 1, roles: ['admin'] } }; const next = { user: { id: 1, roles: ['admin'] } }; isEqual(prev, next); // true, no stringify tricks needed fast-deep-equal is roughly 4-8x faster than JSON.stringify in most benchmark suites, especially with nested structures. Practical takeaway: Pick your comparison tool based on data shape. Use fast-deep-equal for plain objects, Lodash isEqual when you need Date, RegExp, or Map support. What comparison method are you currently using in your React or Node projects - and have you actually benchmarked it? #JavaScript #WebDevelopment #FrontendDevelopment #JSPerformance #NodeJS #CodeQuality
To view or add a comment, sign in
-
💡Don't Use Array Spread Operator In Every Case💡 Yes, you heard that right. If you have a very large data set, then using array spread operator to create a new array will slow down your application and you might receive, "Maximum call stack size exceeded" error. So instead of using array spread operator, use array concat method. const largeArray = [/* your large array */]; const newArray = [/* additional items */]; // Using spread operator (slow for large arrays) const combinedArray1 = [...largeArray, ...newArray]; // Using concat method (more efficient for large arrays) const combinedArray2 = largeArray.concat(newArray); So If you have a very large array, then avoid using spread operator, instead use array concat method. This is because spread operator creates a new array which means each spread operator like …arr1, …arr2 will create a new array and then iterates and then returns a new array. For example, with const result = […arr1, …arr2], javascript will create three arrays one for the result and one for each spread operator (and then iterates it) If we use the same for concat method then there would be one array creation which is result meaning the concat method directly iterates the array. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #typescript #webdevelopment
To view or add a comment, sign in
Explore related topics
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