How I Finally Understood JavaScript Rest Parameters (...args)
As a beginner learning JavaScript, I was confused when I first saw the ...args syntax. I thought it was something very advanced. After practising, I realised it is actually simple and very useful.
What is a Rest Parameter?
A rest parameter allows us to collect multiple arguments into a single array.
Example:
function showNumbers(...numbers) {
console.log(numbers);
}
showNumbers(10, 20, 30, 40);
Output:
[10, 20, 30, 40]
The ...numbers syntax collects all values and stores them in an array called numbers.
Why Use Rest Parameters?
Sometimes we don't know how many values a user will pass to a function.
For example:
sum(10, 20);
sum(10, 20, 30);
sum(10, 20, 30, 40, 50);
Instead of creating many parameters, we can use a rest parameter.
Example: Sum All Numbers
function sum(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(sum(10, 20, 30, 40));
Output:
100
What I Learned
-
...argscollects multiple values. - Rest parameters create an array.
- They are useful when we don't know the number of arguments.
- They are commonly used in modern JavaScript.
As a beginner, practising small examples helped me understand this concept much better than just reading the theory.
Top comments (0)