Advertisement
xerocool-101

005 spread operator

Apr 20th, 2025 (edited)
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 0.77 KB | Software | 0 0
  1. // Array
  2. // Copy array   [...arr]
  3. // Merge arrays [...a, ...b]
  4. // Add elements [1, ...arr, 4]
  5. // In React state   setState([...old, newValue])
  6.  
  7. // Object
  8. // Copy { ...obj }  New object, same values
  9. // Add/Update   { ...obj, key: value }  New or updated property added
  10. // Merge    { ...obj1, ...obj2 }    Combines both (right one wins on key)
  11. // Immutability Used in state updates   Avoids mutation of original object
  12.  
  13. // React
  14. const [user, setUser] = useState({ name: "Alice", age: 25 });
  15. setUser(prev => ({ ...prev, age: 26 }));
  16.  
  17. // Shallow Copy Warning
  18. const obj1 = { user: { name: "Alice" } };
  19. const obj2 = { ...obj1 };
  20.  
  21. obj2.user.name = "Bob";
  22.  
  23. console.log(obj1.user.name); // "Bob" ❗️
  24. // Spread only makes a shallow copy, not deep clone. Nested objects are still shared.
Tags: JavaScript
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement