Functions · Lesson 16 of 45
Parameters: default, rest and spread
Default values, any number of inputs, and spreading arrays.
7 minutes3 games
- default:
function greet(name = "friend")uses the default when no value is passed. - rest
...argsin the definition collects extra arguments into an array. - spread
...arrin a call unpacks an array into separate values.
JavaScript
function greet(name = "friend") {
return `Hello, ${name}!`
}
console.log(greet())
console.log(greet("Hana"))
function sum(...nums) {
let total = 0
for (const n of nums) total += n
return total
}
console.log(sum(1, 2, 3, 4))
const scores = [70, 95, 88]
console.log(Math.max(...scores))
console.log([...scores, 100])[70, 95, 88]
...scores
Math.max(70, 95, 88)
Spread unpacks the array into separate values.
What's the output?
function f(a, b = 10) {
return a + b
}
console.log(f(5))
console.log(f(5, 1))What will this code print?
Complete the code
Collect every argument into an array called items.
function list(items) { return items.length }
Exercise
Write average(...nums) returning the mean, then print average(10, 20, 30) (20).
Expected output: 20
JavaScript
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.