- 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 theaveragefunction in a variable:
let f = average
Then you can call the function:
let result = f(6, 7)
When the expressionf(6, 7)is executed, the contents offis found to be a function. That function is called with arguments6and7.
We can later put another function into the variablef:
f = Math.max
Now when you computef(6, 7), the answer becomes7, the result of callingMath.maxwith the provided arguments.
Here is an example of passing a function as an argument. Ifarris 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)
setsresultto
[0, 1, 1.4142135623730951, 2]
Themapmethod is sometimes called ahigher-order function: a function that consumes another function.