Categories
JavaScript Basics

Spreading Arrays with JavaScript

Spread the love

The spread operator is one of the best recent JavaScript features.

In this article, we’ll look at what we can do with the spread operator.

Spread Operator

Rhe spread syntax lets us expand iterable objects like arrays and strings in various situations.

Merging Arrays

We can merge arrays with it.

For example, we can write:

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

We put all the items from a and b into a new array and assign it to c .

So c is:

[1, 2, 3, 4, 5, 6]

Clone Array

Another way we can use it is to shallow copy an array.

For example, we can write:

const arr = [1, 2, 3];
const arrCopy = [...arr];

We made a copy with the spread operator. It expands the arr entries into a new array.

So arrCopy is also [1, 2, 3] .

But they reference different objects in memory.

Arguments to Array

The arguments object is an iterable object that has the arguments passed into a JavaScript function.

It’s only available in a traditional function.

For instance, we can write:

function foo() {
  const args = [...arguments];
  console.log(args);
}

args is an array.

So if we have:

foo(1, 2, 3)

Then args is [1, 2, 3] .

A more modern alternative that works with all functions is the rest operator:

const foo = (...args) => {
  console.log(args);
}

Then if we call it the same way:

foo(1, 2, 3)

args would have the same value.

String to Array

We can convert a string into an array of characters with the spread operator since string are iterable.

For example, we can write:

const string = 'hello world';
const array = [...string];

Then array is:

["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

Set to Array

A set is an iterable object that can’t have duplicate entries.

Since it’s iterable, we can use the spread operator with it.

For example, we can write:

const set = new Set([1, 2, 2, 3, 3]);
const arr = [...set];

Then arr is [1, 2, 3] since the duplicates are removed from the set.

Map to Array

Maps are key-value pairs that’s stored in an object.

It’s also iterable so we can use the spread operator with it.

For example, we can write:

const map = new Map([
  ['foo', 1],
  ['bar', 2]
]);
const arr = [...map];

We spread the map with the operator and arr would be:

[
  ['foo', 1],
  ['bar', 2]
]

Node List to Array

Node lists are a list of DOM nodes.

It’s an iterable object but it’s not an array.

To convert them to an array, we can write:

const nodeList = document.querySelectorAll('div');
const nodeArr = [...nodeList];

We convert the node list returned from querySelectorAll to an array with the spread operator.

Conclusion

We can use the spread operator to spread or copy arrays and convert iterable objects to arrays.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *