In this post, I’ll discuss the rest and spread operators, represented by the three dots ...
, which are incredibly useful in daily coding.
Let’s dive in and explore how to 'spread' objects and arrays and handle function parameters efficiently.
What is the Spread Operator in JavaScript?
The spread operator (...
) allows elements of an array or properties of an object to be expanded in places where lists of values are expected.
With this, we can easily copy, combine, or modify arrays and objects.
Example of Using the Spread Operator with Arrays
Let’s say you have two arrays:
const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
To combine them into a single array, you can use the spread operator:
const combinedNumbers = [...numbers1, ...numbers2];
console.log(combinedNumbers); // [1, 2, 3, 4, 5, 6]
Here, we spread out the elements of both arrays, creating a new array, combinedNumbers
.
Copying an Array with the Spread Operator
If you want to create a shallow copy of an array, you can use the spread operator:
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
Now copiedArray
is a new array containing the same elements as originalArray
but is independent of it.
The Spread Operator with Objects
The spread operator also works with objects (since ES2018). You can use it to copy or merge objects.
Example of Copying an Object
const originalObject = { a: 1, b: 2 };
const copiedObject = { ...originalObject };
We spread the properties of originalObject
into a new object copiedObject
.
Merging Objects
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const combinedObject = { ...obj1, ...obj2 };
console.log(combinedObject); // { a: 1, b: 2 }
What is the Rest Operator in JavaScript?
The rest operator (...
) allows you to gather multiple arguments into a single function parameter.
This is especially useful when writing functions that take an undefined number of arguments.
Rest Parameter in Functions
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(4, 5, 6, 7)); // 22
Here, the parameter ...numbers
collects all the arguments passed into an array numbers
.
Rest and Spread Operators in Practice
Passing Arguments to Functions
Suppose you have a function that expects three arguments:
function introduce(a, b, c) {
console.log(`Hello, I am ${a}, ${b}, and ${c}.`);
}
You have an array with three names:
const names = ["Ania", "Bartek", "Cezary"];
You can spread this array as function arguments:
introduce(...names);
// Hello, I am Ania, Bartek, and Cezary.
Combining Rest and Spread
You can also use the rest operator alongside other parameters:
function greet(greeting, ...names) {
names.forEach((name) => {
console.log(`${greeting}, ${name}!`);
});
}
greet("Hello", "Ania", "Bartek", "Cezary");
// Hello, Ania!
// Hello, Bartek!
// Hello, Cezary!
Using Rest and Spread Operators with Arrays and Objects
Adding Elements to an Array
Suppose you want to add an element at the beginning of an array:
const originalArray = [2, 3, 4];
const newArray = [1, ...originalArray];
console.log(newArray); // [1, 2, 3, 4]
Updating Object Properties
You have a user object and want to update its name
:
const user = { name: "Jan", age: 30 };
const updatedUser = { ...user, name: "Piotr" };
console.log(updatedUser); // { name: 'Piotr', age: 30 }
Using Spread with Strings
The spread operator can also be used with strings:
const str = "hello";
const chars = [...str];
console.log(chars); // ['h', 'e', 'l', 'l', 'o']
Rest Parameter with Destructuring
const [first, ...restOfNumbers] = [10, 20, 30, 40];
console.log(first); // 10
console.log(restOfNumbers); // [20, 30, 40]
Practical Uses
Creating Copies of Objects and Arrays
The spread operator is useful for creating copies, preventing modification of the original object or array.
Passing an Unlimited Number of Arguments
With the rest operator, you can write functions that handle any number of arguments, which is useful in many situations.
Summary
The rest and spread operators allow you to expand the contents of objects and arrays or collect multiple arguments into a single function parameter.
- Spread operator (
...
): Expands elements of an array or properties of an object. - Rest operator (
...
): Gathers multiple arguments into a single parameter.
I hope this article helped you get to know and understand the rest and spread operators in JavaScript.
Good luck, and see you in the next article!