Clean β’ Professional
In JavaScript, parameters and arguments are the mechanism through which functions accept input values. Understanding how they work is essential for writing flexible, reusable, and maintainable code.
Example:
// Function with parameters
function greet(name, age) {
return `Hello, ${name}! You are ${age} years old.`;
}
// Function invocation with arguments
console.log(greet("Alice", 25)); // Hello, Alice! You are 25 years old.
undefined values and makes functions more robust.function greet(name = "Guest", age = 18) {
return `Hello, ${name}! You are ${age} years old.`;
}
console.log(greet("Alice", 25)); // Hello, Alice! You are 25 years old.
console.log(greet("Bob")); // Hello, Bob! You are 18 years old.
console.log(greet()); // Hello, Guest! You are 18 years old.
Both use the ... syntax but serve distinct purposes in function parameters and arguments.
...)function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(4, 5, 6, 7, 8)); // 30
Notes:
arguments.length....)const numbers = [1, 2, 3];
console.log(Math.max(...numbers)); // 3
function greetAll(a, b, c) {
console.log(`Hello ${a}, ${b}, and ${c}!`);
}
greetAll(...numbers); // Hello 1, 2, and 3!
| Feature | Rest Operator | Spread Operator |
|---|---|---|
| Purpose | Collects multiple arguments into an array | Expands an array into individual elements |
| Usage | Function parameters | Function calls, array literals, object literals |
| Syntax | ...args | ...array |
Handling multiple arguments:
function multiplyAll(...nums) {
return nums.reduce((acc, val) => acc * val, 1);
}
console.log(multiplyAll(2, 3, 4)); // 24
Passing arrays to functions:
const values = [10, 20, 30];
console.log(Math.min(...values)); // 10
Default values in APIs:
function createUser(name = "Anonymous", role = "User") {
return { name, role };
}
console.log(createUser()); // { name: "Anonymous", role: "User" }Β