1. Rest Parameters (...)
- Rest parameters allow a function to accept an indefinite number of arguments as an array.
- Syntax uses three dots (
...) before the parameter name.
✅ Example:
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
🔹 Here, numbers becomes an array of all passed arguments.
Key Points:
- Rest parameter must be the last parameter in the function.
- It collects extra arguments into a single array.
2. Default Parameters
- Default parameters allow you to give default values to function parameters, if no value or
undefinedis passed.
✅ Example:
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet("Himanshu"); // Hello, Himanshu
greet(); // Hello, Guest
🔹 If no argument is passed, name defaults to "Guest".
Key Points:
- Works only if the argument is
undefined(not if it’snull). - Can be any value: string, number, object, function.
⚡ Combined Example (Rest + Default)
function introduce(greeting = "Hi", ...names) {
console.log(greeting + ", " + names.join(", "));
}
introduce("Hello", "Ram", "Shyam", "Geeta");
// Hello, Ram, Shyam, Geeta
introduce(undefined, "Aman", "Ravi");
// Hi, Aman, Ravi
👉 So in short:
- Rest parameters → collect multiple arguments into an array.
- Default parameters → set a fallback value if argument not provided.
