I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Destructuring values returned by functions

Posted on

If a function returns an object, we can destructure the result to take out only the values we need. We don’t need to assign the returned value to an object first.

// 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
// 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
Debug
none
Grid overlay