Lesson 12 / 38

Parameters & First-Class Functions

Default and rest parameters, and functions as values.

Default parameters

Give a parameter a fallback value that's used when the argument is omitted.

function greet(name = "Guest") {
  return `Hello, ${name}!`;
}
console.log(greet());        // Hello, Guest!
console.log(greet("Ada"));   // Hello, Ada!

Rest parameters

...args collects any number of extra arguments into a real array.

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4));  // 10

Functions are values

JS functions are first-class — store them in variables, pass them as arguments, or return them from other functions.

Passing functions around

A function that takes or returns another function is called a higher-order function.

function operate(a, b, fn) {
  return fn(a, b);
}
console.log(operate(4, 2, (a, b) => a - b));  // 2