Member-only story
The spread operator is one of the most useful features introduced in ECMAScript 2015 (ES6). It allows us to easily extract elements from an array or properties from an object, and include them as arguments when calling functions, or merge them into new arrays and objects.
This guide will help you understand what the spread operator is, and how to use it effectively in your projects.
What is the Spread Operator?
The spread operator ...
is used to expand elements of an iterable collection like arrays, strings, or objects into individual elements. When using the spread operator within an expression, it returns a shallow copy of the original iterable. The syntax consists of three periods ...
, followed by the name of the iterable.
Array Examples:
Let’s start by looking at some common uses of the spread operator with arrays.
Copying Arrays:
const arr1 = ['a', 'b', 'c'];
const arr2 = [...arr1]; // creates a copy of arr1
console.log(arr2); // ["a", "b", "c"]
// Changing values in arr2 won't affect arr1…