JavaScript Spread Operator Explained

The JavaScript spread operator is a way to expand an array or list into a concatenable type. This will make more sense after looking at a few examples and code snippets. If you do not understand arrays or lists within JavaScript please read this post first – Arrays and Lists in JavaScript

If we want to combine two arrays in JavaScript we can use the Concat function, which stands for concatenation. This function does not affect the arrays, it returns a new array with the combination of the two arrays. The ‘result’ variable in the code snippet below will contain an array with the number 1 through 10 inside.

We can achieve the same thing by using the spread operator. The spread operator is represented by three dots/periods (…). To concatenate two arrays we first create a new array by using two square brackets, then the first element we use the spread operator on the first array and we do the same with the 2nd element and 2nd array. The spread operator will expand the arrays into there elements. So the ‘result’ variable will contain the number 1 through 10, as before.

If we didn’t use the spread operator, as shown below. The ‘result’ array would contain two arrays, inside of 10 numbers. The first element would contain an array/list of the number 1 through 5 and the second element will be another list with the number 6 through 10.

You can also combine raw values and a spread operator to create a new array. The below result variable will contains a list of number from -2 to 5. This is because we are adding the raw value -2, -1, and 0 and then concatenating the ‘arr1’ list using a spread operator.

You can also use array methods, such as the filter function, in combination with the spread operator to create really custom lists. The below ‘result’ variable will contain a list of number from 3 to 6. Without the spread operator the result variable would contain two arrays instead of a list of just numbers.

2 thoughts to “JavaScript Spread Operator Explained”

Leave a Reply to Carl Cancel reply