
Spread Syntax in JavaScript (...)

When working with iterables in JavaScript (such as arrays, objects or strings), it can be handy to use the spread operator to cut down on code and keep everything readable. Spread syntax allows you to pass the elements of an iterable (for example the elements within an array), through to a function individually. In simplest terms, it means you can write functionality essentially like foreach loops with a single expression and operator.
The spread operator, ..., can be used in a variety of situations to work with iterables ‑ so let's take a look at a few of those now:
Concatenation
The spread operator allows you to combine two or more arrays into a single one very easily, for example:
const arrayOne = [1, 2, 3];const arrayTwo = [4, 5, 6];const arrayThree = [...arrayOne, ...arrayTwo];console.log(arrayThree);// [object Array] (6)// [1,2,3,4,5,6]Easy‑peasy!
Function Calls
Concatenation is certainly useful, but there are definitely better uses out there for this operator. For instance, getting the biggest number from an array:
const arrayOne = [2, 4, 6, 8];console.log(Math.max(...arrayOne));//=> 8...or running it through a function you've built yourself:
const arrayOne = [1, 2, 3, 4, 5];const addUp = (a, b, c, d, e) => { console.log(a + b + c + d + e);};addUp(...arrayOne);//=> 15Obviously, this is a fairly rudimentary example, but suffice it to say: there is a tonne of ways to use this operator besides a pretty ugly addition function!
The Wrap‑Up
The JavaScript spread syntax is a nifty little operator to handle iterables, and can really help clean up your code, make it nicer to write, and make it easier to read.
One thing to bear in mind though is that you'll have some issues using it in IE (of course).
Categories:
Related Articles

The Safest Way to Test for NaN. The Safest Way to Test for

Rest and Spread Operators in JavaScript: A Beginner's Guide. Rest and Spread Operators in JavaScript: A Beginner's Guide

LeetCode: Removing the nth Node from the End of a List. LeetCode: Removing the
nthNode from the End of a List
JavaScript Array Manipulation: slice() vs. splice(). JavaScript Array Manipulation:
slice()vs.splice()
Understanding the Module Pattern in JavaScript. Understanding the Module Pattern in JavaScript

Handling API Routes in Next.js: When to Use Server Actions vs. API Routes. Handling API Routes in Next.js: When to Use Server Actions vs. API Routes

Manipulating Strings in JavaScript with split(). Manipulating Strings in JavaScript with
split()
Using Vue's Teleport for Modals and Portals. Using Vue's Teleport for Modals and Portals

Finding the Median of Two Sorted Arrays with JavaScript. Finding the Median of Two Sorted Arrays with JavaScript

The Power of text‑wrap: pretty. The Power of
text‑wrap: pretty
Check If Your Site is Running on localhost. Check If Your Site is Running on
localhostHandling Click Events in JavaScript. Handling Click Events in JavaScript