Using the ternary operator in assignment and return

The ternary operator can be used when assigning variables or even as part of return statements. It can help us make some arrow functions even shorter.

const isEven = n => n % 2 === 0

// assigning the result of a ternary operator to a variable
const numberType = isEven(35) ? 'even' : 'odd'

// returning the result of a ternary operator in a function
const getNumberType = number => {
  return isEven(number) ? 'even' : 'odd'
}

// returning the result of a ternary operator using an implicit return
const getNumberType = number => isEven(number) ? 'even' : 'odd'

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.