Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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.

  • + Share This
  • 🔖 Save To Your Account