Parameters & Arguments
Pass data into functions with parameters.
Syntax
function greet(name = 'Guest') { ... }Parameters are named inputs listed in a function's definition. The values you pass when calling are the arguments.
Default parameters
Give a parameter a default value with =. It is used when no argument is provided.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- Pass a user object and a message string as arguments to a notification function.
- Use rest parameters to accept a variable number of score arguments in a high-score tracker.
- Provide a default page size parameter so callers can omit it when the default is sufficient.
More examples
Multiple parameters
Defines a function with three parameters and calls it with matching positional arguments.
function sendEmail(to, subject, body) {
console.log(`To: ${to}\nSubject: ${subject}\n\n${body}`);
}
sendEmail("[email protected]", "Welcome", "Thanks for joining!");Default parameter value
Uses a default parameter so callers can omit pageSize and get 10 items, or pass a custom value.
function paginate(items, pageSize = 10) {
return items.slice(0, pageSize);
}
const results = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
console.log(paginate(results).length); // 10 β default
console.log(paginate(results, 5).length); // 5 β overrideRest parameters for variadic args
Uses rest parameters (...numbers) to accept any number of arguments and sum them all.
function sum(...numbers) {
return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
Discussion