Rest Pattern And Parameters In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Rest Pattern And Parameters In JavaScript.
Rest Pattern And Parameters In JS
In JavaScript, the rest operator (represented by three dots: “…”) is used to gather the remaining elements of an array into a new one. It can also be used to gather the remaining properties of an object into a new one. For example, in the following code snippet:
function myFunction(a, b, ...args) {
console.log(a);
console.log(b);
console.log(args);
}
myFunction(1, 2, 3, 4, 5);
The first two arguments, 1 and 2, are assigned to the variables “a” and “b” respectively. The rest operator “…” gathers the remaining arguments (3, 4, and 5) into an array called “args”. The output of the function would be:
Output
1
2
[3, 4, 5]
The parameters in Javascript are the variables that are used in the function definition. The values passed to the function when it is invoked are assigned to these parameters. In the above example, a and b are the parameters of the function myFunction.
Difference between spread and rest operator
The spread operator (represented by three dots: “…”) and the rest operator (also represented by three dots: “…”) may look similar, but they are used in different ways.
The spread operator is used to expand an iterable (such as an array or string) into its individual elements. For example, you can use the spread operator to spread the elements of an array into multiple variables, or to concatenate multiple arrays into one.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
Output
[1, 2, 3, 4, 5, 6]
On the other hand, the rest operator is used to gather multiple elements into a single array or object. It is often used in function arguments to gather all remaining arguments into an array.
function myFunction(a, b, ...args) {
console.log(args);
}
myFunction(1, 2, 3, 4, 5);
Output
[3, 4, 5]
Conclusion
In summary, the spread operator is used to spread out elements of an iterable, while the rest operator is used to gather multiple elements into a single array or object.