Function Parameters
Parameters act as placeholders for values passed to a function when it is called.
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 8
console.log(add(10, 20)); // 30
Try it Yourself →
Default Parameter Values
ES6 introduced default parameters, which are used when no argument or undefined is passed.
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet()); // Hello, Guest!
Multiple Defaults
You can set defaults for as many parameters as needed.
function createUser(name = "User", role = "viewer", active = true) {
return { name, role, active };
}
console.log(createUser("Bob", "admin"));
// { name: "Bob", role: "admin", active: true }
Rest Parameters
Rest parameters (...args) collect all remaining arguments into a real array.
function sumAll(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sumAll(1, 2, 3, 4, 5)); // 15
console.log(sumAll(10, 20)); // 30
Rest with Named Parameters
Rest must always be the last parameter.
function listFruits(category, ...items) {
console.log("Category: " + category);
console.log("Items: " + items.join(", "));
}
listFruits("tropical", "mango", "papaya", "coconut");
// Category: tropical
// Items: mango, papaya, coconut
The arguments Object
In non-arrow functions, the arguments object holds all passed arguments (array-like, not a real array).
function showArgs() {
for (let i = 0; i < arguments.length; i++) {
console.log("Arg " + i + ": " + arguments[i]);
}
}
showArgs("a", "b", "c");