How to Use JavaScript's Spread Operator

Apr 14, 2021

JavaScript's spread operator, ..., is a handy way to pass multiple values from an array, object, or anything you can iterate through to a function or variable assignment. It shines especially when you want to combine two or more arrays. The ... operator offers a more intuitive way to combine multiple arrays than using push(), splice(), or concat():

const array1 = ['a', 'b'];
const array2 = ['c', 'd'];
const array3 = [...array1, ...array2, 'e', 'f'];
array3; // ['a','b','c','d','e','f']

Note: Avoid using ... with multidimensional arrays. Modifying that kind of an array can lead to problems like shown below:

let arr1 = [[1],[2],[3]];
let arr2 = [...arr1];
arr2.shift().shift();
arr2; // [[2], [3]]
arr1; // [[], [2], [3]]

Spread with Functions

The spread operator also lets you call a function with the contents of an array as parameters, similar to apply(). it passes the arguments of the iterable value to the function in order and if you have more than it is expecting, it does not create any problems.

function test(arg1,arg2) {
  return arg1 + ' ' + arg2;
}
const args = ['Hello', 'World'];
test(...args); // Hello World

Spread with Objects

The same use case with arrays applies to objects as well, so long as there is more than one property in the object. Another ability that the spread operator enables is shallow cloning an object. Essentially, with regards to nested objects, any changes made on the copy are reflected onto the original.

const obj = { answer: 42 };
// The `Object.assign()` function is a common way to shallow clone an object
const copy = Object.assign({}, obj);

++copy.answer; // 43
obj.answer; // 42, did not change because `copy` is a copy of `obj`
const obj = { name: { first: 'Jean-Luc', last: 'Picard' } };
const copy = Object.assign({}, obj);

copy.name.first = 'Johnny';
obj.name.first; // 'Johnny', `name` was **not** cloned

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!