Summary - Parameters
Write a flexible order summary function using default and rest parameters.
Summary - Parameters
In this group you learned flexible use of function parameters. With a default parameter you set a value for a missing argument; with a rest parameter you gather unlimited arguments into an array. You met the legacy arguments object and why rest is preferred.
You also saw that a function can return multiple values via an array or object, and that splitting big problems into small helper functions makes code readable. Now you will combine all of this in an order summary function.
Exercise Order summary function
Define a function called orderSummary. It should take a unitPrice = 10 default parameter and a ...quantities rest parameter. Inside, initialize let total = 0, loop with for (let q of quantities) and add each amount with total += q * unitPrice. Then return the summary with return total.
Show example solution
function orderSummary(unitPrice = 10, ...quantities) {
let total = 0;
for (let q of quantities) {
total += q * unitPrice;
}
return total;
}
Exercise Call the order summary
The orderSummary function below is defined. Now call it and print the results. First use console.log(orderSummary(undefined, 2, 3, 5)) to use the default price; undefined as the first argument triggers the default. Then use console.log(orderSummary(20, 1, 1, 1, 1)) for a custom price.
Show example solution
function orderSummary(unitPrice = 10, ...quantities) {
let total = 0;
for (let q of quantities) {
total += q * unitPrice;
}
return total;
}
console.log(orderSummary(undefined, 2, 3, 5));
console.log(orderSummary(20, 1, 1, 1, 1));
Test yourself
-
Which is a rest parameter syntax?
- function sum(...nums)
- function sum(nums[])
- function sum(...nums[])
- function sum(*nums)
Show answer
function sum(...nums) — Correct. ...nums is the rest parameter and turns all arguments into an array.
-
Match the concepts
- name = "Guest"
- Default parameter
- ...nums
- Rest parameter
- arguments[0]
- Legacy object
- return [a, b]
- Returns an array