6 Use Cases of Spread with Array in JavaScript

samanthaming

Samantha Ming

Posted on June 30, 2020

6 Use Cases of Spread with Array in JavaScript

Alt Text

Here are 6 ways to use the Spread operator with Array in JavaScript. You can use it to merge or clone an array. Or use it to convert iterables to an array.

// Merge Array
[...array1, ...array2]

// Clone Array
[...array]

// Sting โ†’ Array
[...'string']

// Set  โ†’ Array
[...new Set([1,2,3])]

// Node List โ†’ Array
[...nodeList]

// Arguments โ†’ Array
[...arguments]

Understanding Spread

MDN: Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Clear as mud right ๐Ÿ˜‚ Spread took me a long time to understand. So let me try to explain with 2 analogies that helped me. Hopefully, it can also help you ๐Ÿคž

Spread is like Russian Dolls

The spread syntax takes your array and expands it into elements. Imagine your array is like those Russian Dolls. When you call the spread syntax on it, it will take the nested individual doll out and lay it out in its own individual pieces.

Credit: Wikipedia

Spread is like an Eraser

If the Russian Dolls analogy didn't help and Spread is still muddy for you ๐Ÿ˜ต In that case, just think of the ... syntax as an eraser that removes the brackets of the array ๐Ÿ˜‚

[
  ...[1, 2, 3] // ๐Ÿ‘ˆ The dots erases the brackets
]

/*  Becoming this: */
[
  1, 2, 3 // ๐Ÿ‘ˆ "Erased"
]

Array Manipulation

The best thing about the Spread syntax is to use it for array manipulation ๐Ÿ‘

1. Use Spread for Merging Array

Let's say we have 2 arrays.

const array1 = [1, 2, 3];

const array2 = [4, 5, 6];

Let's see what happens when we try to merge the array without the spread syntax.

const attemptToMerge = [array1, array];

attemptToMerge;
// [ [1, 2, 3],  [4, 5, 6] ] ๐Ÿ‘ˆ ๐Ÿ˜ฑ

๐Ÿ‘† When you try to merge an array without the spread syntax, you wind up with a nested or multi-dimensional array.

So let's use the Spread syntax to "erase" the brackets.

const mergedArray = [
  ...array1,
  ...array2
];

mergedArray;
// [ 1, 2, 3, 4, 5, 6 ]

2. Clone Array

Cloning array in JavaScript isn't as straight forward. So let's see it done in 2 paths - the wrong way and the right way ๐Ÿ›ฃ

Cloning Array the Wrong Way

In JavaScript, arrays are reference types, so you can't just create a new copy of an array using =. Let's see what problem happens if we try to do it that way.

const original = ['zero', 'one'];
const newArray = original;

original; // ['zero', 'one']
newArray; // ['zero', 'one']

๐Ÿ‘†So everything looks okay so far, but let's see what happens if we change the element.

newArray[1] = '๐Ÿ’ฉ';

newArray;
// ['zero', '๐Ÿ’ฉ']

original;
// ['zero', '๐Ÿ’ฉ']  ๐Ÿ‘ˆ ๐Ÿ˜ฑ Our original array is affected

OH yikes ๐Ÿ˜ฑ Changing the newArray will mutate the original array ๐Ÿ‘Ž

Think of references as addresses. When we create a copy of an array using =, we've only copied the address. We have NOT copied the underlying array, which is what we want. To do that, we need to copy the array at a new address. That way, when we make changes to our new array, it won't affect the original array -- because they're at different addresses.

Cloning Array the Right Way

const original = ['zero', 'one'];
const newArray = [...original];

original; // ['zero', 'one']
newArray; // ['zero', 'one']

So if we did this correctly, our original array shouldn't be affected if we changed the newArray. Alright, let's give this a try ๐Ÿ’ช

newArray[1] = '๐Ÿ’ฉ';

newArray;
// ['zero', '๐Ÿ’ฉ']

original;
// ['zero', 'one']  โœ… original array is NOT affected

Iterables to Array

With Spread, converting different data types to an Array has never been easier ๐Ÿ‘

3. String to Array

When we spread a string, it will return an array of individual substrings.

const string = 'hi';

const array = [...string];

array;
// [ 'h' , 'i' ]

4. Set to Array

Let's create a new set object:

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

set;
// Set(3) {1, 2, 3}

Using Spread, we can convert the set into an array:

const array = [...set];

array;
// [1, 2, 3]

5. Node List to Array

Let's create a node list:

const nodeList = document.querySelectorAll('p');

nodeList;
// [p, p, p]

Now we can use Spread to convert our node list into an array:

const array = [...nodeList];

array;

6. Arguments to Array

Before we begin, let's take some time to understand what the arguments objects is.

MDN: arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function.

๐Ÿ‘† Notice the key there, array-like -- So it looks like an array, but it isn't (oh JS, always making things so fun for us to understand you ๐Ÿ˜…). The benefit of converting the arguments object to an array means we have access to all the awesome array methods (ie. map, filter, find) ๐Ÿ‘

function names() {
  arguments;
  // Arguments(4)['samantha', 'sam']

  arguments.map(name => `hi ${name}`);
  // โŒ TypeError: arguments.map is not a function
}

names('samantha', 'sam');

Alright, let's convert our arguments into an array so we can apply array methods on it ๐Ÿ™Œ

function names() {
  const argumentsArray = [...arguments];

  argumentsArray.map(name => `hi ${name}`);
  // โœ… ['hi samantha', 'hi sam']
}

names('samantha', 'sam');

Community Input

  • @harmleprinze: Split will give more options, considering it takes in separator and limit

  • @mohammed_mamoun_98: If you merged two arrays without spread it's gonna be two-dimensional array but flat make it one dimension so it's more effective I guess. You can try it

  • @bukazoltan: The min() and max() method cannot take an array as an input, so spreading it can solve that problem too... It saved me a lot of headaches.

array = [1, 2, 3, 4, 5];
var minimum = Math.min(...array);
var maximum = Math.max(...array);

Resources


Thanks for reading โค
Say Hello! Instagram | Twitter | SamanthaMing.com

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
samanthaming
Samantha Ming

Posted on June 30, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How JavaScript works
javascript How JavaScript works

November 8, 2024

A Beginner's Guide to JavaScript Closures
javascript A Beginner's Guide to JavaScript Closures

November 5, 2024

Type Coercion in JavaScript Explained
javascript Type Coercion in JavaScript Explained

November 18, 2024

Introduction to Asynchronous JavaScript
javascript Introduction to Asynchronous JavaScript

October 14, 2024

Strings -- Manipulating the Immutable.
javascript Strings -- Manipulating the Immutable.

November 15, 2024

ยฉ TheLazy.dev

About