Function Parameters
A parameter can have a default value that is used when the argument is missing. A rest parameter (...nums) collects the remaining arguments into an array.
For functions with many options, accept one object and read named properties from it. This is easier to read than a long list of positions.
Example
function greet(name = "friend") {
return "Hello, " + name;
}
console.log(greet());
console.log(greet("Ada"));
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4));
function box({ width = 1, height = 1 } = {}) {
return width * height;
}
console.log(box({ width: 4, height: 5 }));Exercise
Collect any number of arguments.
function total(nums) {}
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.