Using the ternary operator in assignment and return

Posted on

We can use the ternary operator to assign variables or even as part of return statements. The if-else version of achieving the same result would often take a lot more lines of code.

The ternary operator can also help us make some arrow functions even shorter.

const isEven = n => n % 2 === 0
 
/*
 * Conditionally assigning a value to a variable
 */
 
// before
let numberType
 
if (isEven(35)) {
  numberType = "even"
} else {
  numberType = "odd"
}
 
// after
const numberType = isEven(35) ? "even" : "odd"
 
 
/*
 * Conditionally returning a result in a function
 */
 
// before
const getNumberType = number => {
  if (isEven(number)) {
    return "even"
  } else {
    return "odd"
  }
}
 
// after
const getNumberType = number => {
  return isEven(number) ? "even" : "odd"
}
 
// after (with implicit return)
const getNumberType = number => isEven(number) ? "even" : "odd"
const isEven = n => n % 2 === 0
 
/*
 * Conditionally assigning a value to a variable
 */
 
// before
let numberType
 
if (isEven(35)) {
  numberType = "even"
} else {
  numberType = "odd"
}
 
// after
const numberType = isEven(35) ? "even" : "odd"
 
 
/*
 * Conditionally returning a result in a function
 */
 
// before
const getNumberType = number => {
  if (isEven(number)) {
    return "even"
  } else {
    return "odd"
  }
}
 
// after
const getNumberType = number => {
  return isEven(number) ? "even" : "odd"
}
 
// after (with implicit return)
const getNumberType = number => isEven(number) ? "even" : "odd"
Debug
none
Grid overlay