In this tutorial, we will explore the concept of the spread operator, which is employed to unpack elements from an iterable like an array, string, or object. The spread operator is denoted by three dots (…).
Let's explore an illustration that does not involve the utilization of the spread operator:
Let's instantiate an array named 'fruits' and then display its contents without utilizing the spread operator.
Example
let fruits = ['mango', 'apple', 'pear'];
console.log(fruits[0], fruits[1], fruits[2]);
Output:
mango apple pear
Explanation:
In the previous illustration, we displayed every element from the 'fruits' array by referencing their respective index numbers.
Next, we will explore a demonstration showcasing the utilization of the spread operator:
Let's define an array named 'fruits' and display its contents by utilizing the spread syntax.
Example
let fruits = ['mango', 'apple', 'pear'];
console.log(...fruits);
Output:
mango apple pear
Explanation:
In this instance, we have opted not to utilize index numbers for displaying all items; rather, we have employed spread operators. It is evident that this approach results in a more concise and tidier code structure.
Benefits of the spread operator
We can use the spread operator for many things, which are as follows:
- It can be utilized to access all items in an array.
- It can be utilized to combine arrays.
- It can be utilized to pass elements to functions as separate arguments.
- It can be utilized to create a shallow copy of object literals.
- It can be utilized to merge object literals.
Below are a few examples showcasing the utilization of the spread operator in JavaScript:
Demo 1: Expanding the Array
In this demonstration, we will elaborate on the components of an array.
Example
let colors = ["red", "blue", "yellow"];
// without using the spread operator
console.log(colors);
// using the spread operator
console.log(...colors);
Output:
[ 'red', 'blue', 'yellow' ]
red blue yellow
Explanation:
In the example provided, a variable called colors has been declared using the let keyword. It has been displayed in two ways: one without employing the spread operator and the other with the spread operator.
Demo 2: Spread Operator inside Array
Expanding the contents of an array can be achieved by employing the spread operator within the array.
Example
let colors = ["red", "blue", "yellow"];
// add colors array to colors1
// without using the spread operator
let colors1 = ["orange", colors, "brown"];
// spread colors array within colors2 array
// using the spread operator
let colors2 = ["orange", ...colors, "brown"];
console.log(colors1);
console.log(colors2);
Output:
[ 'orange', [ 'red', 'blue', 'yellow' ], 'brown' ]
[ 'orange', 'red', 'blue', 'yellow', 'brown' ]
Explanation:
The spread operator has not been utilized to display the colors1 array, revealing the presence of a nested array within it.
The colors2 array has been displayed using the spread operator, allowing us to observe that the elements from the colors array are now separate string elements.
Demo 3: Duplicating Object Literals
In this demonstration, we will make use of the spread operator to replicate object literals.
Example
const cars_company = {
company1: 'BMW',
company2: 'Tesla',
company3: 'Ferrari'
};
// without using the spread operator
const companies1 = {cars_company};
// using the spread operator
const companies2 = {...cars_company};
console.log(companies1);
console.log(companies2);
Output:
{ cars_company: { company1: 'BMW', company2: 'Tesla', company3: 'Ferrari' }}
{ company1: 'BMW', company2: 'Tesla', company3: 'Ferrari' }
Explanation:
In the example provided, an object called cars_company has been instantiated using the const keyword. The object literals have been replicated in two manners: one without employing the spread operator and the other utilizing the spread operator. The replication of the object literals can be observed in the output display.
Demo 4: Merging Object Literals
In this demonstration, we will make use of the spread operator to combine object literals.
Example
let student1 = { name : 'Ben', age : '25' };
let student2 = { name : 'Katy', age : '36' };
// using the spread operator to merge student1 and student2 into team1
let team1 = {... student1, ... student2};
// without using the spread operator to merge student1 and student2
let team2 = { student1, student2};
console.log("team1 =", team1);
console.log("team2 =", team2);
Output:
team1 = { name: 'Katy', age: '36' }
team2 = {
student1: { name: 'Ben', age: '25' },
student2: { name: 'Katy', age: '36' }
}
Explanation:
By utilizing the spread operator, we combined student1 and student2 into team1, resulting in a seamless merging of both objects to create a fresh object.
By combining student1 and student2 into team2 without utilizing the spread operator, we are able to access the names of both objects.
Demo 5: Spread Operator as Part of Function Argument
Utilizing the spread operator within function arguments is a common practice. Let's define a function that accepts three arguments.
Example
// function that takes three arguments
function sum(number1, number2 , number3) {
console.log(number1 + number2 + number3);
}
let numbers = [2, 6, 10, 9];
// pass the first three array elements
sum(...numbers);
Output:
Explanation:
In the example provided, the spread operator was utilized within a function argument. A function called "sum" was defined for this purpose. The arguments were passed both by utilizing the spread operator and printing the resulting output.
Demo 6: Spread Operator with Strings
In this demonstration, we will showcase the utilization of the spread operator with strings.
Example
const movie = "zathura";
//without using the spread operator
const adventure1 = [movie];
// using the spread operator
const adventure2 = [...movie];
console.log(adventure1);
console.log(adventure2);
Output:
[ 'zathura' ]
[
'z', 'a', 't',
'h', 'u', 'r',
'a'
]
Explanation:
In the demonstration provided earlier, a constant variable called movie was established using the const keyword. We then showcased the spreading of a string both without utilizing the spread operator and with the spread operator.
Difference between Spread Operator and Rest Operator
Occasionally, there can be confusion distinguishing between the rest operator and the spread operator as they both share a common syntax of three dots (…). However, it is important to note that these operators serve distinct purposes.
| Spread Operator | Rest Operator |
|---|---|
| The spread operator is very useful for expanding an iterable. For example, strings, objects, and arrays.Example:const myArray = [1,2,4,6];console.log(...myArray,12,14);Output:1 2 4 6 12 14Explanation:In the upper example, we have defined a variable namedmyArrayusingconst. We have then assigned it to an array. With the help of the spread operator, we can expand and print it into its individual elements. | The rest operator is used to collect multiple arguments into an array or an object.Example:function addNum(...num) {let total = 0;for (const digit of num){total += digit;}return total;}console.log(addNum(1,3,5));Output:9Explanation:In the above example, we have defined a function named addNum, which takes a parameter. We have utilized the rest operator to get multiple arguments. |
Conclusion:
In this guide, we have explored the spread operator functionality in JavaScript. We have examined different methods of applying the spread operator through practical examples.
Listed below are some of the commonly asked queries:
- What is the main purpose of the spread syntax?
In JavaScript, the spread operator is denoted by three dots (…) and serves to unpack an iterable into separate elements. Its common applications include merging arrays and cloning object literals.
- Under what circumstances should we avoid employing the spread operator?
Avoid utilizing the spread operator for generating a deep copy as it solely produces a shallow copy. Refrain from employing it within loops that are critical for performance to prevent any adverse effects on performance.
- What is the release date of the spread operator?
The ES6 introduced the spread operator in JavaScript, which is a valuable feature for unpacking iterables into separate elements.
- What is the purpose of the spread operator when used for arguments?
The spread operator in JavaScript is a valuable tool for simplifying the process of passing arguments of variable lengths to functions. By employing the spread operator with an argument, there is no requirement to pass each argument separately; instead, an array of values can be unpacked into function parameters.
What constraints, if any, exist for the spread operator?
Despite its versatility, the spread operator does have certain constraints. It is not suitable for handling multidimensional arrays or objects containing nested arrays or objects. The spread operator is limited to a single level of depth, meaning it can only work with one level of nested data structures.