Object Spread

Object Spread
πŸ‘¨β€πŸ’Ό Object spread is how we update objects without mutation. This is critical for React state updates where mutation doesn't trigger re-renders.
// Create a new object with updated values
const original = { name: 'Alice', age: 30 }
const updated = { ...original, age: 31 }
// updated = { name: 'Alice', age: 31 }
// original is unchanged!

Order Matters

Later properties override earlier ones:
const defaults = { theme: 'light', fontSize: 14 }
const userPrefs = { fontSize: 18 }
const settings = { ...defaults, ...userPrefs }
// { theme: 'light', fontSize: 18 }

Nested Objects

Spread is shallowβ€”nested objects need explicit spreading:
const user = { name: 'Alice', address: { city: 'NYC' } }
const updated = {
	...user,
	address: { ...user.address, city: 'LA' },
}
🐨 Open
index.ts
and:
  1. Create updatedUser by spreading user and setting email to 'alice.new@example.com' β€” leave the original user unchanged
  2. Create finalConfig by merging defaultConfig then userConfig so user values win (timeout should be 10000, other fields from defaults)
  3. Create userWithDarkMode by immutably updating nested settings.theme to 'dark' while keeping notifications: true β€” leave user.settings.theme as 'light'
  4. Export updatedUser, user, finalConfig, and userWithDarkMode
Spread syntax lets you create new objects from existing ones.

Please set the playground first

Loading "Object Spread"
Loading "Object Spread"
Login to get access to the exclusive discord channel.
Loading Discord Posts