Spread and Rest Operator- What’s the Difference?
SPREAD OPERATOR
The spread operator in Javascript, denoted by three dots (…), is a powerful addition to JavaScript. It serves as a tool to expand iterables, such as arrays or strings, in places where more than zero arguments are expected. Unlike the rest parameter, the spread operator cuttings values from an array. Let’s study the syntax and discover various use cases.
Syntax:
var variableName=[...value]
In this syntax, the three dots (…) mean the spread operator, pointing all values in the detailed variable.
Usage of Spread Operator in Different Cases
1. Spread Operator and Array Manipulation
Constructing array literal
When creating an array using the literal form, the spread operator simplifies the insertion of another array within the initialized array.
let Numbers = ['1', '2'];
let new_Numbers = [... Numbers, '3', '4', '5'];
console.log(new_Numbers);
Output:
['1', '2', '3', '4', '5']
Concatenating arrays
The spread operator can concatenate two or more arrays.
let arr1 = ['1', '2'];
let arr2 = ['3', '4', '5'];
let combine_arr = [...arr1, ...arr2];
console.log(combine_arr);
Output:
['1', '2', '3', '4', '5']
Replication an array
The spread operator enables copying the case of an array.
let arr1 = ['1', '2'];
let arr2 = [...arr1];
console.log(arr2);
//Output: [ '1', '2']
When replication arrays without the spread operator, implanting a new element in the replicated array affects the original array. However, using the spread operator confirms that the original array remains unaffected.
Without using a spread operator
let arr1 = ['1', '2'];
let arr2 = arr1;
arr2.push('3');
console.log(arr2);
console.log(arr1);
Output:
['1', '2','3']
['1','2', '3']
Using spread operator
let arr1 = ['1', '2'];
let arr2 = [...arr1];
arr2.push('3');
console.log(arr2);
console.log(arr1);
Output:
['1', '2','3']
['1','2']
Note: The spread operator performs a shallow copy, copying the array itself rather than its elements.
Spread Operator and Strings
The spread operator can also be useful to strings, spreading out each character into different elements.
let str = ['s', ...'PREA', 'D'];
console.log(str);
Output: [ 'S', 'P', 'R', 'E', 'A', 'D']
REST OPERATOR
Introduced in ES2015 (ES6), the rest parameter is a robust feature in JavaScript that greatly enhances the adaptability of handling function parameters. It allows functions to accept a variable number of arguments, neatly bundled within an array, regardless of the function’s initial structure. The syntax employs three dots (…) before the parameter name, presenting a more dynamic and flexible approach to managing function parameters.
Here’s an explanation and a few examples :
Function Parameters
Example 1:
function add(a, b) { return a + b; }
console.log(add(1, 2));
// Output: 3
console.log(add(1, 2, 3, 4, 5));Â //Â Output:Â 3
In the first example, passing more arguments than parameters doesn’t throw an error, but only the first two arguments are considered. This behavior changes when using the rest parameter.
Example 2:
function sum(...numbers) {
let total = 0;
for (let num of numbers) {
total += num; }
return total;
}
console.log(sum(1, 2)); // Output: 3
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(1, 2, 3, 4, 5));Â //Â Output:Â 15
In the second example, the rest parameter (…numbers) gathers all provided arguments, consolidating them into an array. This enables us to iterate through the array and compute their cumulative sum.
Rest Parameter with Other Parameters
Example 3:
function printDetails(firstName, lastName, ...otherDetails) {
console.log(${firstName} ${lastName}); // Mukul Latiyan
console.log(otherDetails); // [ 'Lionel', 'Messi', 'Barcelona' ]
console.log(otherDetails[0]); // Lionel
console.log(otherDetails.length); // 3
console.log(otherDetails.indexOf('Lionel')); //0
}
printDetails('Mukul', 'Latiyan', 'Lionel', 'Messi', 'Barcelona');
Within this illustration, the rest parameter (…otherDetails) assembles any extra arguments beyond the initial two. Upon utilization, the rest parameter generates an array (otherDetails) amenable to manipulation using array methods. It’s imperative to highlight that the rest parameter should occupy the final position in the parameter list, as its role is to gather any outstanding arguments into an array. Any attempt to position it elsewhere will lead to an error. This rest parameter offers a concise and efficient method for handling diverse quantities of function arguments.
Difference between Rest and Spread operator
Feature | Rest Operator (…) | Spread Operator (…) |
Syntax | Gather the remaining function parameters into an array. | Spreads elements of an array or object into separate variables or properties. |
Function Parameters | Used in function parameters to collect extra arguments. | Not applicable in function parameters. |
Array Destructuring | Collects remaining elements into a designated array. | Spreads elements of an array into distinct variables. |
Object Usage | Not the primary choice for object operations. | Spreads properties from one object into another. |
Example | javascript function example(…args) { // Rest Operator // Code using args array } | javascript const arr1 = [1, 2, 3]; const arr2 = […arr1, 4, 5]; // Spread Operator |
Use Cases | Effective for handling variable function parameters with an unknown number of arguments. | Useful for creating array copies, merging arrays, or spreading object properties. |
Position in Syntax | Found in the function parameter list to aggregate additional arguments. | Placed before an iterable (array or object) to disseminate its elements. |
Iteration Approach | Typically used with iteration for processing the collected elements. | Spreads elements without iteration, copying them individually. |
Join our Best MERN Stack Course program and become an expert in web development career. This Course is for beginners who want to learn web development from the Basics. We cover all the aspects of web development of Web development. This Course is fully packed with amazing content.