CodeBlanks Logo Icon CodeBlanks

Object spread

Learn to merge and copy objects with ....

Object spread

The spread operator ... copies all properties of an object into another object literal. It is a concise way to merge and copy objects.

The syntax is { ...source, extra: value }. Here every property of source is copied into the new object, then extra is added. If a property with the same name appears both in the source and later, the later one wins.

Example: const a = { x: 1 }; const b = { ...a, y: 2 };. Now b is { x: 1, y: 2 }. The original a is unchanged; spread produces a shallow copy.

Shallow copy and merging

The copy made by spread is shallow: only the top-level properties are copied. Nested objects are copied by reference, so changing a nested object affects both the original and the copy.

Example: const a = { profile: { name: 'Ayşe' } }; const b = { ...a }; b.profile.name = 'Mara';. Now a.profile.name is also 'Mara', because profile is the same object in both.

To merge two objects, chain spreads: { ...a, ...b }. Properties of b override the same-named ones from a. This is enough for simple merges.

Practice Merge profiles

Define base as { name: 'Ayşe', city: 'İstanbul' }. Define extra as { age: 30, city: 'İzmir' }. Use spread to merge them into a merged object (extra's city wins). Print merged.city with console.log.

Starter code

index.js
// Define base and extra, merge with spread, print city

Sample solution

index.js
const base = { name: 'Ayşe', city: 'İstanbul' };
const extra = { age: 30, city: 'İzmir' };
const merged = { ...base, ...extra };
console.log(merged.city);

Expected output

İzmir

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the spread parts

Term Meaning
... Spread operator
{ ...a, y: 2 } Merge
a Source object
y: 2 Property added later

2 What does spread do?

  • Copies properties into a new object Correct answer
  • Deletes the object
  • Adds methods
  • Changes the type

Explanation: spread copies properties into a new object.

3 Override with spread

Question
const base = { age: 30 };
const updated = { ...base, age: ____ };
Answer
const base = { age: 30 };
const updated = { ...base, age: 31 };

Explanation: age: 31 given later overrides the previous 30.

All lessons in Beginner