0 day streak
javascript / intermediate
Snippet

Object Immutability with Spread and Rest

Maintaining immutability is crucial for predictable state management. Combining rest syntax to exclude properties and spread syntax to merge new ones allows you to derive new state without modifying the original object.

snippet.js
javascript
1
2
3
4
5
6
7
8
const state = { id: 1, name: 'Original', extra: 'to be removed' };
// Remove a property and update another while keeping state immutable
const { extra, ...rest } = state;
const newState = { ...rest, name: 'Updated', status: 'active' };
console.log(state);
console.log(newState);
Breakdown
1
{ extra, ...rest } = state
Uses rest destructuring to pull 'extra' out and group all remaining properties into the 'rest' object.
2
{ ...rest, name: 'Updated' }
Creates a shallow copy of the 'rest' object and overrides the 'name' property in the resulting new object.