Spread Operator in JavaScript

Level 4224 keystrokes

This uses the spread operator to combine arrays and merge objects.

JavaScript code

// Two separate arrays
1const arr1 = [1, 2, 3];
2const arr2 = [4, 5, 6];
// Spread operator ... expands array elements
// Creates a new array with all elements from both arrays
3const combined = [...arr1, ...arr2];
// Result: [1, 2, 3, 4, 5, 6]
4console.log(combined);
5
// Two separate objects
6const obj1 = { a: 1, b: 2 };
7const obj2 = { c: 3, d: 4 };
// Spread operator expands object properties
// Creates a new object with all properties
8const merged = { ...obj1, ...obj2 };
// Result: { a: 1, b: 2, c: 3, d: 4 }
9console.log(merged);

Output

[ 1, 2, 3, 4, 5, 6 ]
{ a: 1, b: 2, c: 3, d: 4 }
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.

  • .× 14
  • ,× 8
  • ;× 8
  • =× 6
  • :× 4
  • [× 3
  • ]× 3
  • {× 3
  • }× 3
  • (× 2

More JavaScript examples at level 4

← JavaScript typing practice