- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
3.2 Higher-Order Functions
JavaScript is a functional programming language. Functions are values that you can store in variables, pass as arguments, or return as function results.
For example, we can store the average function in a variable:
let f = average
Then you can call the function:
let result = f(6, 7)
When the expression f(6, 7) is executed, the contents of f is found to be a function. That function is called with arguments 6 and 7.
We can later put another function into the variable f:
f = Math.max
Now when you compute f(6, 7), the answer becomes 7, the result of calling Math.max with the provided arguments.
Here is an example of passing a function as an argument. If arr is an array, the method call
arr.map(someFunction)
applies the provided function to all elements, and returns an array of the collected results (without modifying the original array). For example,
result = [0, 1, 2, 4].map(Math.sqrt)
sets result to
[0, 1, 1.4142135623730951, 2]
The map method is sometimes called a higher-order function: a function that consumes another function.