Merging with Object.assign in JavaScript

Level 4228 keystrokes

Object.assign() copies properties from sources to target, with later sources overwriting earlier ones.

JavaScript code

// Create target and source objects
1const target = { a: 1, b: 2 };
2const source1 = { b: 3, c: 4 };
3const source2 = { c: 5, d: 6 };
// Object.assign merges objects left to right
// Using {} as target creates a new object
// b: 3 overwrites b: 2, c: 5 overwrites c: 4
4const result = Object.assign({}, target, source1, source2);
// Print merged object { a: 1, b: 3, c: 5, d: 6 }
5console.log(result);
// Original target is unchanged
6console.log(target);
// result is a new object, not the same as target
7console.log(result === target);

Output

{ a: 1, b: 3, c: 5, d: 6 }
{ a: 1, b: 2 }
false
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ;× 7
  • =× 7
  • ,× 6
  • :× 6
  • .× 4
  • (× 4
  • )× 4
  • {× 4
  • }× 4

More JavaScript examples at level 4

← JavaScript typing practice