avatarDr. Derek Austin 🥳

Summary

The web content provides a comprehensive guide on the usage and benefits of the spread operator (...) in JavaScript, introduced in ES6 (ES2015), which facilitates array copying, concatenation, object combination, and more.

Abstract

The article "How to Use the Spread Operator (…) in JavaScript" delves into the functionality and applications of the spread operator, a versatile feature that allows developers to expand iterable objects into individual elements. It explains how the spread operator can be used to copy arrays, combine arrays or objects, pass elements as function arguments, and work with mathematical functions. The author emphasizes the operator's utility in everyday JavaScript tasks, such as adding items to arrays, using Math functions, and managing React state. The article also addresses the operator's limitations with deeply-nested objects and provides solutions for older browser compatibility, advocating for its use by JavaScript developers for cleaner and more efficient code.

Opinions

  • The author positively endorses the spread operator as a time-saving tool that enhances code expressiveness and ease in JavaScript development.
  • The spread operator is praised for its ability to create new array instances without retaining references to the original array, preventing unexpected behavior.
  • The article acknowledges the spread operator's limitation in creating deep copies of nested objects, suggesting libraries like lodash or Ramda for such cases.
  • The author recommends using Babel with the babel-plugin-transform-spread for compatibility with older browsers that do not support the spread operator.
  • The author expresses a personal preference for using the spread operator when adding items to React state and when combining object properties, highlighting these as favorite use cases.

How to Use the Spread Operator (…) in JavaScript

The spread operator is a useful and quick syntax for adding items to arrays, combining arrays or objects, and spreading an array out into a function’s arguments.

Photo by Ethan Robertson on Unsplash

What is the spread operator?

In JavaScript, spread syntax refers to the use of an ellipsis of three dots () to expand an iterable object into the list of arguments.

“When ...arr is used in the function call, it ‘expands’ an iterable object arr into the list of arguments.” — JavaScript.info

The spread operator was added to JavaScript in ES6 (ES2015), just like the rest parameters, which have the same syntax: three magic dots .

Photo by Sumner Mahaffey on Unsplash

What is ... used for?

“Spread operator to the rescue! It looks similar to rest parameters, also using ..., but does quite the opposite.” — JavaScript.info

Take trying to find the largest number in an array with Math.max():

Trying to pass an array to a JavaScript function expecting separate arguments does not work. In this case it produces a NaN result. Enter :

The spread syntax “spreads” the array into separate arguments.

Photo by Joanna Szumska on Unsplash

What else can … do?

The spread operator is useful for many different routine tasks in JavaScript, including the following:

  • Copying an array
  • Concatenating or combining arrays
  • Using Math functions
  • Using an array as arguments
  • Adding an item to a list
  • Adding to state in React
  • Combining objects
  • Converting NodeList to an array

In each case, the spread syntax expands an iterable object, usually an array, though it can be used on any interable, including a string.

Photo by Wojciech Portnicki on Unsplash

Examples of using …

Here are a couple basic examples of using in JavaScript, where I demonstrate copying an array, splitting a string into characters, and combining the properties of two JavaScript objects:

In the next section, I explore each of the above uses of the spread syntax.

Photo by Lopez Robin on Unsplash

Copying an array

Using the spread operator is a convenient way to copy an array or combine arrays, and it can even add new items:

Photo by Pineapple Supply Co. on Unsplash

Concatenating arrays

As seen in the last example, the spread operator can quickly combine two arrays, an operation known as array concatenation:

Photo by Joe Cooke on Unsplash

Using Math functions

“The Math object's set of functions are a perfect example of the spread operator as the only argument to a function.” — @davidwalshblog on his blog

One of the best ways to understand the use of spread operator in JavaScript is to look at the the built-in functions Math.min() and Math.max(), which both expect a list of arguments, not an array.

Photo by Ben Warren on Unsplash

Using an array as arguments

Since the spread operator “spreads” an array into different arguments, any functions that accepts multiple any number of arguments can benefit from use of the spread operator.

Photo by Lacie Slezak on Unsplash

Adding an item to a list

As noted in the last example, the spread operator can add an item to an another array with a natural, easy-to-understand syntax:

Photo by Mickey O'neil on Unsplash

Adding to state in React

Adding an item to an array in React state is easily accomplished using the spread operator. Take the following example adapted from my article on how to add to an array in React State:

Photo by Lukasz Szmigiel on Unsplash

Combining objects

The spread syntax is useful for combining the properties and methods on objects into a new object:

Photo by Fezbot2000 on Unsplash

Converting NodeList to Array

The spread operator can convert NodeList and arguments objects to arrays, such as when selecting HTML elements on the page:

Photo by frank mckenna on Unsplash

The spread operator and older browsers

When programming to support Internet Explorer and browsers on older mobile devices, the spread operator is not going to work.

Here is the current browser compatibility chart:

In that case, the function Function.prototype.apply() will have the same effect as the spread syntax:

Note that the first argument to .apply() is the target for this, which in this case does not matter, so I passed in null as the first argument.

Another option would be using the tool Babel to compile the JavaScript code along with the plugin babel-plugin-transform-spread.

Photo by Rowan Heuvel on Unsplash

A note about copying by reference

One of the benefits of using the spread operator is that it will create a new reference to its primitive values, copying them.

That means that changes to the original array will not affect the copied array, which is what would happen if the array had been linked to the original with the assignment operator =:

As you can see, the spread operator is useful for creating new instances of arrays that do not behave unexpectedly due to old references.

Photo by Jenna Day on Unsplash

Watch out for the deeply-nested Gotcha!

On the other hand, when JavaScript objects including arrays are deeply nested, the spread operator only copies the first level with a new reference, but the deeper values are still linked together.

This type of problem is called creating a deep copy, as opposed to a shallow copy. Deep copies can be made using lodash or the R.clone() method from the Ramda functional programming library.

Thanks to Michał Bargiel for pointing out that the spread operator makes a shallow copy but not a deep copy.

Photo by Scott Webb on Unsplash

Conclusion

“The spread operator can expand another item by split an iterable element like a string or an array into individual elements:” — CodinGame.com

The spread operator is useful for working with arrays and objects in JavaScript. It is a convenient feature added in ES6 (ES2015).

One of my favorite uses of the spread syntax is when combining arrays such as when adding an item to React State.

I also like that it can quickly combine the properties of objects into a new object, though any properties whose names conflict will be lost.

Knowing the spread syntax definitely saves me time when coding, and I recommend using it to all JavaScript developers.

Photo by Anastasia Taioglou on Unsplash

Further reading

Photo by Mink Mingle on Unsplash

Join my email list to get free access to all of my Medium articles.

JavaScript
Programming
Software Engineering
Technology
Web Development
Recommended from ReadMedium