Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Usage of rest parameter and spread operator in JavaScript?
Rest parameters and spread operators use the same three-dot syntax (...) but serve different purposes. Rest parameters collect multiple arguments into an array, while spread operators expand arrays or objects into individual elements.
Rest Parameters
Rest parameters allow functions to accept an indefinite number of arguments as an array. They must be the last parameter in a function's parameter list.
Syntax
function functionName(...parameterName) {
// parameterName is an array containing all arguments
}
Example
<html>
<body>
<script>
function addition(...numbers) {
var res = 0;
numbers.forEach(function (number) {
res += number;
});
return res;
}
document.write("Sum of 3: " + addition(3) + "<br>");
document.write("Sum of multiple: " + addition(9, 10, 11, 12, 13));
</script>
</body>
</html>
Sum of 3: 3 Sum of multiple: 55
Spread Operator
The spread operator expands arrays, strings, or objects into individual elements. It's useful for function calls, array literals, and object literals.
Syntax
// Function calls
myFunction(...iterableObj);
// Array literals
[...iterableObj, 4, 5, 6];
// Object literals
{...obj, key: value};
Example with Function Arguments
<html>
<body>
<script>
function multiply(x, y) {
return x * y;
}
var myArgs = [50, 100];
document.write("Result: " + multiply(...myArgs));
</script>
</body>
</html>
Result: 5000
Example with Array Combination
<html>
<body>
<script>
var a = [10, 20];
var b = "rank";
var c = [30, "points"];
var d = "run";
// Using concat method
var e = a.concat(b, c, d);
// Using spread operator
var f = [...a, b, ...c, d];
document.write("Concat result: " + e + "<br>");
document.write("Spread result: " + f);
</script>
</body>
</html>
Concat result: 10,20,rank,30,points,run Spread result: 10,20,rank,30,points,run
Key Differences
| Feature | Rest Parameters | Spread Operator |
|---|---|---|
| Purpose | Collect arguments into array | Expand array/object elements |
| Usage | Function parameters | Function calls, arrays, objects |
| Position | Must be last parameter | Can be used anywhere |
Conclusion
Rest parameters simplify handling variable arguments in functions, while spread operators provide a clean way to expand arrays and objects. Both features make JavaScript code more readable and flexible.
