We have previously discussed rest parameters and spread operators. They have a similar appearance, yet each has its functionality. We'll go over their differences and applications.
Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element
Let's discuss rest parameters and spread operator before discussing their differences:
Rest Parameters:
Rest parameters should be preferred in modern programming instead of argument operator.
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.
A function definition's last parameter can be prefixed with ...
, which will cause all remaining (user-supplied) parameters to be placed within an Array
object.
function demo(...args) {
console.log(args);
}
demo(1, 2, 3, 4, 5);
// output:- [ 1, 2, 3, 4, 5 ]
Spread Operators:
The spread syntax works within array literals, function calls, and initialized property objects to spread the values of iterable objects into separate items.
Use of Spread Operator to convert string intro individual array elements.
const myname = "suraj gaire"
console.log([...myname])
//output:- ['s','u','r','a','j',' ','g','a','i','r','e']
Rest vs Spread Operator in function calls:
Spread Operator in function calls:
Replace apply()
It is common to use Function.prototype.apply()
in cases where you want to use the elements of an array as arguments to a function.
function myfunction(a,b,c){
console.log(arguments)
}
const args = [0,1,2]
myfunction.apply(null,args)
// Output:- [Arguments] { '0': 0, '1': 1, '2': 2 }
With spread syntax, the above can be written as:
function myfunction(a,b,c){
console.log(arguments)
}
const args = [0,1,2]
myfunction(...args)
// Output:- [Arguments] { '0': 0, '1': 1, '2': 2 }
Rest Parameters in function calls:
function demo(...args) {
console.log(args)
}
demo("a", "b", "c", "d");
// Output :- [ 'a', 'b', 'c', 'd' ]
Copy an array:
Using Spread Operator:
const arr = [1,2,3,4]
const a = [...arr]
Using Rest Parameters:
function demo(...args) {
const arr = args
console.log(arr)
}
demo("a", "b", "c", "d");
They may look like same but they have their use cases:
Rest parameters were introduced to reduce the boilerplate code that was commonly used for converting a set of arguments to an array.
The Spread operator is a powerful array literal. It can be used to perform array operations like an array concatenation copy array easily and it can be used in object literals to clone or merge objects.