I am sure that you have heard of the spread operator in Javascript (...) It's one of the most powerful operators in Javascript it offers and can solve many problems like the ten you will find the below.
The spread operator can be used to solve multiple problems you might encounter in javascript. This article will teach you how to do the following operations using the spread operator
In the basic form , the spread operator looks like three dots.
[...arr];
- Copy an array
- Combine arrays
- Add an item to an array
- Adding a property to an object
- Use Math() functions
- Spread array as function arguements
- Pass unlimited arguements to a functions
- Destructuring an object
- Exploding a string
Copy an array
Let’s say we have an array called arr1, and we want to make a clone of this array called arr2.
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [...arr1, 6, 7, 8, 9, 10];
console.log(arr2);
// [1, 2, 3, 4, 5,6, 7, 8, 9, 10];
So this way, we can copy a basic array, but be aware it doesn’t work for multi-level arrays or arrays with dates or functions
Note: Read more about deep cloning in Javascript
Combine arrays
Let’s say you have two arrays that you want to merge into one, this happens quite often, and we could use the concat method. The spread operator makes this way easier, as you can see below.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
// [1,2,3,4,5,6];
So now the two arrays (arr1, arr2) are combined into arr3.
Add an item to an array
Let’s say you have an array but need to add one or multiple items. You can leverage the Array.push, but the spread operator will also work fine.
let arr1 = ["this", "is", "an"];
arr1 = [...arr1, "array"];
// ['this','is','an','array']
As you can see, this will add the new string to the end of our existing array.
You can even pass multiple strings.
arr1 = [...arr1, "array", "smart"];
console.log(arr1);
// ['this','is','an','array','smart']
Adding a Property to an object
Let’s say you have an object of a user, but it’s missing an age property.
const user = {
firstName: "John",
lastName: "Doe",
};
We can again the spread operator to add the age to this user object
const output = { ...user, age: 25 };
What happens above is that we spread the user object and add a new property called age to it with the value of 25.
const user = {
firstName: "John",
lastName: "Doe",
};
const output = { ...user, age: 25 };
console.log(output);
// {firstName:"John",lastName:"Doe",age:25};
Use Math functions
Let’s say you have an array of numbers and want to get the lowest, highest, or the sum of these numbers.
That’s another excellent option for the spread operator to shine.
Our input array will look like this
const arr1 = [1, -1, 0, 5, 3];
To get the lowest number, we can use the spread operator and the Math.min method.
const arr1 = [1, -1, 0, 5, 3];
const min = Math.min(...arr1);
console.log(min);
// -1
This will output -1 because that’s the lowest number. Try and remove the -1 from the array. You’ll see the lowest will become 0.
To get the highest number we can use the Math.max method.
const arr1 = [1,-1,0,5,3];
const max = Math.max[...arr1];
console.log(max);
// 5
Spread array as function arguments
Sometimes you have a function that expects separate arguments, but you have them in an array. The spread operator lets you pass the array elements as individual arguments.
function multiply(a, b, c) {
return a * b * c;
}
const numbers = [2, 3, 4];
const result = multiply(...numbers);
console.log(result); // 24
Pass unlimited arguements to a functions
When defining a function, you can use the rest parameter (which looks like spread) to collect any number of arguments into an array. This is often combined with spread for powerful patterns.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
Destructuring an object
Spread can be used to extract properties from an object while keeping the rest together.
const person = { name: "Alice", age: 30, city: "New York", country: "USA" };
const { name, age, ...location } = person;
console.log(name); // Alice
console.log(age); // 30
console.log(location); // { city: 'New York', country: 'USA' }
Exploding a string
Spread can turn a string into an array of its characters
const str = "hello";
const chars = [...str];
console.log(chars); // ['h', 'e', 'l', 'l', 'o']