The Spread Operator (…) was introduced in ES6
The ...
is the spread syntax that allows you to specify an array that should be split and have its items passed in as separate arguments to a function.
The spread operator allows expanding elements of an array or object into places where multiple elements are expected.
According to the MDN:
The spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
Examples:
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // [1, 2, 3, 4, 5]
JavaScriptlet arr = [1, 2, 3, 4, 5];
function multiply(a, b, c, d, e) {
return a * b * c * d * e;
}
// spreads the array as seperate parameters
console.log(multiply(...arr)); // 120
JavaScriptFind the largest number from the given array of numbers
Before ES6
The ideal solution will be to use Math.max with apply method
let arr = [1,2,3,4,5];
console.log(Math.max.apply(null, arr)); // 5
JavaScriptThe solution works perfect but it is bit confusing.
With ES6
ES6 Spread operator (…) makes this very easy and simple
let arr = [1,2,3,4,5];
// using spread operator (...)
console.log(Math.max(...arr)); // 5
JavaScriptJavascript Engine split’s arr in to individual arguments.
Combining multiple arrays
With javascript spread operator (…) it is easy to combine multiple arrays.
let arr = [1,2,3,4,5];
let arr2 = [6,7,8,9,10];
let combine = [...arr, ...arr2];
// [1,2,3,4,5,6,7,8,9,10]
let combine2 = [0, ...arr, 11, ...arr2, 12];
// [0,1,2,3,4,5,11,6,7,8,9,10,12]
let combine3 = [...arr, 'sujay', ...arr2];
// [1,2,3,4,5,"sujay",6,7,8,9,10]
JavaScriptThe spread operator … allows us to pass all the items of arr and arr2 at the same time add extra items also.
Copying an array
Drawbacks while copying arrays before ...
spread operators.
let arr = [1,2,3,4,5];
let copy = arr;
console.log(copy); // [1,2,3,4,5];
arr.push(6);
console.log(arr); // [1,2,3,4,5,6];
console.log(copy); // [1,2,3,4,5,6]; // same as arr
JavaScriptWe have added an extra item to arr
with arr.push(6)
but the same gets updated in copy, this happens because arr is never copied to copy but passed as the reference which means copy is just pointing to arr. A seperate solution would be to copy all the items individually using loops.
We can solve this issue with the javascript (…) spread operator.
let arr = [1,2,3,4,5];
let copy = [...arr];
console.log(copy); // [1,2,3,4,5];
arr.push(6);
console.log(arr); // [1,2,3,4,5,6]
console.log(copy); // [1,2,3,4,5]
JavaScriptUse Cases:
- Cloning Arrays
- Merging Arrays
- Destructuring Arrays
- Cloning Objects
- Merging Objects
- Function Arguments (Rest Parameters)
- Combining Objects
- Converting NodeLists to Arrays
- Default Function Arguments
- Flattening Arrays
1. Cloning Arrays
Use Case – You can create a shallow copy of an array using the spread operator. This is useful when you want to preserve the original array while making modifications to the clone.
const arr1 = [1, 2, 3];
const arr2 = [...arr1]; // Cloning arr1 into arr2
arr2.push(4);
console.log(arr1); // [1,2,3]
console.log(arr2); // [1,2,3,4]
JavaScriptIn this example, arr2 is a shallow copy of arr1. Modifying arr2 does not affect arr1.
2. Merging Arrays
Use Case: The spread operator is a clean way to merge two or more arrays into a single array.
Example:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArr = [...arr1, ...arr2];
console.log(mergedArr); // [1,2,3,4,5,6]
JavaScriptThis approach is simpler than using methods like concat() for merging arrays.
3. Destructuring Arrays
Use Case: You can use the spread operator to extract part of an array while keeping the remaining elements in another array.
const [first, ...rest] = [1,2,3,4,5];
console.log(first); // 1
console.log(rest); // [2,3,4,5]
JavaScriptHere, the first element is assigned to first, and the remaining elements are gathered in to the rest array.
4. Cloning Objects
Use Case: Similar to arrays, the spread operator can be used to create a shallow copy of an object.
const obj1 = {
a: 1,
b: 2
}
obj2.c = 3;
console.log(obj1); // { a: 1, b: 2}
console.log(obj2); // { a: 1, b: 2, c: 3}
JavaScriptThis creates a shallow copy of obj1. Any changes made to obj2 won’t affect obj1.
5. Merging Objects
Use Case : The spread operator is commonly used to merge multiple objects in to one.
const obj1 = {
a: 1,
b: 2,
}
const obj2 = {
b: 3,
c: 4
}
const mergedObj = {...obj1, ...obj2};
console.log(mergedObj); // {a: 1, b: 3, c: 4}
JavaScriptWhen merging, properties from obj2 overwrite those from obj1, If there are conflicts (eg. property b).
6. Function Arguments (Rest Parameters)
Use Case: The spread operator can be used to pass an array as individual arguments to a function.
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1,2,3];
console.log(sum(...numbers)); // 6
JavaScriptHere, the spread operator expands the numbers array in to individual arguments.
7. Combining Objects (Immutable State Updates in React)
Use Case: In React, or any functional programming context, spread operators are frequently used to immutably update the state.
const initialState = {
user: 'John',
age: 30
}
// Updating the state with a new age
const updatedState = {
...initialState,
age: 31
}
console.log(updatedState); // { user: 'John', age: 31 }
JavaScriptThis is particularly useful in React’s useState and setState where immutability is essential.
8. Converting NodeLists to Arrays
Use Case – The spread operator can convert array-like structures (like NodeLists) in to actual arrays.
const nodeList = document.querySelectorAll('div'); // NodeList
const nodeArray = [...nodeList] // Now it's an array
console.log(Array.isArray(nodeArray)); // true
JavaScriptThis technique is handy when you want to apply array methods like map, filter, or reduce to a NodeList or other iterable objects.
9. Default Function Arguments
Use Case: You can use the spread operator to easily combine function arguments with default values.
function addDefaults(config) {
const defaultConfig = {
showTitle: true,
theme: 'light'
}
return {
...defaultConfig,
...config
}
}
JavaScriptHere, user-provided values (userConfig) are merged with default ones (defaultConfig), with user values overriding defaults when necessary.
10. Flattening Arrays
Use Case: The spread operator can flatten an array, particularly in cases where you have nested arrays.
const nestedArr = [1, [2,3], [4,5]];
const flattenedArr = [].concat(...nestedArr);
console.log(flattenedArr); // [1,2,3,4,5]
JavaScriptIn this case, the spread operator helps flatten nested arrays by spreading the inner arrays into the outer array.
Key points about the Spread operator (…)
- Shallow Copy : Both for arrays and objects, the spread operator creates a shallow copy, meaning that for nested objects or arrays, only references are copied
- Immutable Pattern : It’s often used in React, and other frameworks to maintain immutability of objects or arrays, which is crucial in functional programming paradigms.
- Functionality Expansion: Besides arrays and objects, the spread operator can also be used with iterables like strings and NodeLists, enhancing its versality.
The spread operator simplifies code and increases readability, making it an essential tool for working with arrays, objects and other iterable structures in modern Javascript.
Pingback: Javascript - ES6 Features - xplor4r