Function Parameters & Arguments in JavaScript
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.
Parameters and Arguments
- Parameters are placeholders defined in the function declaration.
- Arguments are the actual values passed to the function when it is invoked.
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.
Default Parameters
- JavaScript allows default values for parameters if no argument is provided.
- Prevents
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.
Rest and Spread Operators
Both use the ... syntax but serve distinct purposes in function parameters and arguments.
Rest Operator (...
)
- The rest operator allows a function to accept any number of arguments as an array.
- Useful when you don’t know how many arguments a function will receive.
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:
- Must be the last parameter in the function definition.
- Helps create flexible functions without manually checking
arguments.length
.
4. Spread Operator (...
)
- The spread operator is used to expand an array into individual elements, often when calling functions.
- Makes it easy to pass arrays as arguments.
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!
Difference Between Rest and Spread:
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 |
Practical Use Cases
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" }