03 First-class and higher-order functions

Lesson goal Understand the difference between first-class functions, a property of the language, and higher-order functions, which take or return functions, and learn to write your own higher-order functions.

Functions in JavaScript are first-class, and that is what makes higher-order functions possible.

First-class functions are a property of the language: in it, functions are values just like numbers or strings. A function can be assigned to a variable, passed as an argument to another function, and returned from a function.

Higher-order functions is the term commonly used for functions that accept other functions as arguments or return a function.

// A simple example
// ===============================
const data = [1, 2, 3, 4]

// multiply can be passed as an argument to another function,
// because functions in JavaScript are first-class:
// they are values just like numbers or strings
// multiply :: Number -> Number
const multiply = (v) => v * 2

// map is a
// higher-order function,
// because it takes another function
// as an argument
const result = data.map(multiply)

console.log (result) // [2, 4, 6, 8]

In short, a function that takes or returns a function is a higher-order function. "First-class", on the other hand, is not the role a function plays in a call but a property of the language: in JavaScript any function can be passed or returned like an ordinary value.

In React a component is a value (a function or a class), so it can be passed to a function: a higher-order component (HOC) is a function that takes a component and returns a new component. In Vue a component is usually described by an options object rather than a function (only a functional component is a plain function), but the idea is the same: components and slots are passed around as values, and in render functions slots are functions that receive data and return virtual nodes (vnodes).

// A simple example
// ===============================

// hof :: (* -> *) -> * -> *
const hof = (fc) => (...args) => fc (...args)

// hof is a higher-order function:
// it takes the function fc and returns a new function

// fc can be passed to hof because functions
// in JavaScript are first-class

// An example in the spirit of Vue slots (and render props in React)
// MyComponent is a higher-order function: it takes slot functions
// and calls them, passing data to them, like a scoped slot
// This is not a higher-order component (HOC): a HOC takes a component and returns a new component
// A simplified model: real Vue returns virtual nodes, not strings
function MyComponent({ main, default: def } = {}) {
  const greetingMessage = 'hello'

  if (main) {
    return `<div>main - ${ main (greetingMessage)}</div>`
  }

  if (def) {
    return `default - ${def(greetingMessage)}`
  }

  return 'no components'
}

// calling the higher-order function: we pass slot functions to it
const templateMain = MyComponent({
  main: (text) => `XXX${text}XXX`
})

const templateDefault = MyComponent({
  default: (text) => `${text}`
})

console.log(templateMain)    // <div>main - XXXhelloXXX</div>
console.log(templateDefault) // default - hello

Key points

  • First-class functions are a property of the language: in JavaScript, functions are values just like numbers or strings. A function can be assigned to a variable, passed as an argument to another function, and returned from a function.
  • A higher-order function takes another function as an argument or returns a function. map is a higher-order function because it takes another function.
  • "First-class" is not the role a function plays in a call but a property of the language. It is what makes higher-order functions possible in JavaScript.
  • A higher-order component (HOC) in React is a function that takes a component and returns a new component. In Vue render functions, slots are functions that receive data and return virtual nodes.

Exercises

Exercise 1

Write a higher-order function twice: it takes a function fn and returns a new function that applies fn to a value twice. Check it with add3 and double, then pass the result of twice back into twice.

Starter code

// add3 :: Number -> Number
const add3 = (x) => x + 3

// double :: Number -> Number
const double = (x) => x * 2

// twice :: (a -> a) -> a -> a
// your code

console.log(twice(add3)(10))
console.log(twice(double)(5))
console.log(twice(twice(double))(3)) // twice returned a function, so it can be passed to twice again

Expected output

16
20
48
Show solution
// add3 :: Number -> Number
const add3 = (x) => x + 3

// double :: Number -> Number
const double = (x) => x * 2

// twice :: (a -> a) -> a -> a
// takes the function fn and returns a new function
const twice = (fn) => (x) => fn(fn(x))

console.log(twice(add3)(10))
console.log(twice(double)(5))
console.log(twice(twice(double))(3)) // twice returned a function, so it can be passed to twice again

Exercise 2

Write a higher-order function withLog: it takes a name, then a function, and returns a new function that returns the same result as the original one and prints a line like "double(1) = 2". Pass the wrapped function to map, as multiply is passed in the lesson.

Starter code

// double :: Number -> Number
const double = (x) => x * 2

// withLog :: String -> (Number -> Number) -> Number -> Number
// your code

const loggedDouble = withLog('double')(double)

const doubled = [1, 2, 3].map(loggedDouble)

console.log(doubled)

Expected output

double(1) = 2
double(2) = 4
double(3) = 6
[
  2,
  4,
  6
]
Show solution
// double :: Number -> Number
const double = (x) => x * 2

// withLog :: String -> (Number -> Number) -> Number -> Number
// withLog(name) takes the function fn and returns a new one: the same result plus a line in the console
const withLog = (name) => (fn) => (x) => {
  const value = fn(x)
  console.log(`${name}(${x}) = ${value}`)
  return value
}

const loggedDouble = withLog('double')(double)

const doubled = [1, 2, 3].map(loggedDouble)

console.log(doubled)

Playground

Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.

Connected:
playground
Output
—