/

Working with Objects and Arrays Using Rest and Spread

Working with Objects and Arrays Using Rest and Spread

Learn two modern techniques for working with arrays and objects in JavaScript.

You can expand an array, object, or string using the spread operator ....

Let’s start with an example for arrays:

1
const a = [1, 2, 3];

To create a new array, you can use:

1
const b = [...a, 4, 5, 6];

You can also create a copy of an array using:

1
const c = [...a];

This also works for objects. You can clone an object using:

1
const newObj = { ...oldObj };

Using strings, the spread operator creates an array with each character in the string:

1
2
const hey = 'hey';
const arrayized = [...hey]; // ['h', 'e', 'y']

The spread operator has some useful applications. The most important one is the ability to use an array as a function argument in a simple way:

1
2
3
const f = (arg1, arg2) => {};
const a = [1, 2];
f(...a);

In the past, you could achieve this using f.apply(null, a), but that’s not as nice and readable.

The rest element is useful when working with array destructuring:

1
2
const numbers = [1, 2, 3, 4, 5];
[first, second, ...others] = numbers;

And with spread elements:

1
2
3
const numbers = [1, 2, 3, 4, 5];
const sum = (a, b, c, d, e) => a + b + c + d + e;
const sumOfNumbers = sum(...numbers);

In ES2018, rest properties were introduced, which are similar but for objects.

Rest Properties:

1
2
3
4
5
6
7
8
9
10
11
const { first, second, ...others } = {
first: 1,
second: 2,
third: 3,
fourth: 4,
fifth: 5
};

first; // 1
second; // 2
others; // { third: 3, fourth: 4, fifth: 5 }

Spread properties allow you to create a new object by combining the properties of the object passed after the spread operator:

1
2
const items = { first, second, ...others };
items; //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }

tags: [“JavaScript”, “array”, “object”, “rest”, “spread”, “ES2018”]