Destructuring values returned by functions

If a function returns an object, we can destructure the result afterwards. We can take out only the values we need that way.

// this function does some math and returns multiple results
const doSomeMath = array => {
  const sum = array.reduce((sum, value) => sum + value, 0)

  // we return an object with three values instead of just a single value
  return {
    min: Math.min(...array),
    max: Math.max(...array),
    average: sum / array.length
  }
}

// we can pick the values we want; we can skip `min` if we don’t need it
const { max, average } = doSomeMath([15, 4, 23, 16, 42, 8])
// max:     42
// average: 18

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.