Spread and Rest Operator, The three Dots in JavaScript
What Are the Three Dots?
The ... operator can be used in arrays and is a useful syntax that makes data processing more concise, quickly expanding content into a new array. It has two usages:
- Spread Operator
- Rest Operator
The syntax is the same with three dots, but the effects differ based on their positions.
Spread Operator
It can “spread” an array into individual values or convert iterable objects such as String, Array, TypedArray, Map, Set, the arguments in functions, the HTMLCollection and NodeList in the DOM into arrays.
Example 1: Spread and Add Arrays
const foo = [1, 2, 3];const bar = [4, 5, 6];const foobar = [...foo, ...bar]; // [1, 2, 3, 4, 5, 6]Spread the foo and bar arrays and merge them into the foobar array. The spreading is done by shallow copying, meaning the values in the foobar array are copies of the values from the foo and bar arrays, not references. This method of spreading and copying is suitable for creating a new array without modifying the original arrays.
Example 2: As Function Parameters
function addNumbers(a, b, c) { return a + b + c;}
addThreeNumbers(...[0, 1, 2]);The spread values can be used as function parameters, eliminating the need to pass each parameter one by one.
Example 3: Convert Array-Like or Iterable Objects to Arrays
<ul id="list"> <li>1</li> <li>2</li> <li>3</li></ul>const list = document.querySelector('#list');
console.log(list.children);// HTMLCollection(3) [li, li, li]
console.log([...list.children]);// [li, li, li]Or convert some array-like objects into arrays, which allows array-like objects to become true arrays and use array methods.
Rest Operator
The purpose of the rest operator is clear: it is used to collect the remaining parameters into an array, packaging “all remaining” parameters into one array, and it must be the last parameter in the array. If no values are passed, it will be an empty array.
function sum(...numbers) { return numbers.reduce((total, number) => total + number, 0);}
sum(1, 20, 30, 2); // 53Object rest and spread Properties
The rest and spread of arrays are ES6 syntax, while the rest and spread properties of objects are syntax introduced in ES2018, with similar usage.
const obj = { a: 1, b: 2, c: 3, d: 4 };
const { a, b, ...rest } = obj;console.log(a); // 1console.log(b); // 2console.log(rest); // { c: 3, d: 4 }