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

Implicit object return in arrow functions

Posted on

If an arrow function immediately returns a value, we don’t need to write the return keyword. The return is implied if the only statement in the function is a value.

If that value is an object, we need to wrap that object in parentheses for the implicit return to work.

// the `return` is optional in arrow functions that immediately return a value
const explicitAdd = (a, b) => return a + b
const implicitAdd = (a, b) => a + b
 
// this does NOT work when the return value is an object
const myFunction = value => {
  key: value,
  length: value.length
}
// ↑ this does not work
 
// we have to wrap the object in parentheses in this scenario
const myFunction = value => ({
  key: value,
  length: value.length
})
// ↑ this is fine
 
// if anything else happens in the function, like assigning variables or
// calling other functions, we HAVE to be explicit and write the `return`
const myFunction = value => {
  const length = value.length
 
  return {
    key: value,
    length: length
  }
}
// the `return` is optional in arrow functions that immediately return a value
const explicitAdd = (a, b) => return a + b
const implicitAdd = (a, b) => a + b
 
// this does NOT work when the return value is an object
const myFunction = value => {
  key: value,
  length: value.length
}
// ↑ this does not work
 
// we have to wrap the object in parentheses in this scenario
const myFunction = value => ({
  key: value,
  length: value.length
})
// ↑ this is fine
 
// if anything else happens in the function, like assigning variables or
// calling other functions, we HAVE to be explicit and write the `return`
const myFunction = value => {
  const length = value.length
 
  return {
    key: value,
    length: length
  }
}
Debug
none
Grid overlay