Functions: the verbs of your program
Declarations, arrow functions, defaults, rest parameters and functions that take functions.
A function packages a piece of work behind a name. It can take inputs (parameters), do something, and hand a value back with return. A function without a return statement returns undefined.
function double(n) { // declaration, hoisted
return n * 2;
}
const double2 = function (n) { // expression
return n * 2;
};
const double3 = (n) => n * 2; // arrow, shortest formDefaults and rest parameters
function greet(name = "friend") {
return `Hello, ${name}!`;
}
greet(); // "Hello, friend!"
greet("Ada"); // "Hello, Ada!"
function sumAll(...numbers) { // collects every argument
return numbers.reduce((total, n) => total + n, 0);
}
sumAll(1, 2, 3); // 6
sumAll(); // 0Functions are values. You can store them in variables, put them in arrays, and pass them to other functions. A function that takes or returns a function is called a higher-order function — map, filter and reduce are the ones you will use daily.
Try it
Functions are values
Exercises
Checked in your browser · hints and solutions included
Exercise
Apply a function twice
Write applyTwice(fn, value) that calls fn with value, then calls fn again with the first result, and returns the final value.
applyTwice((n) => n + 1, 5) → 7.
Exercise
Sum anything you pass
Write sumAll(...numbers) that returns the total of every argument. With no arguments it returns 0.
sumAll(1, 2, 3) → 6.