markmcdermott.io (js, ruby, ...etc) by mark mcdermott

Double Ternary

10/27/2024

estimated reading time:2 mins

This is might be venturing into JavaScript: The Bad Parts, but I was flummoxed today when ChatGPT answered a question I had with a JavaScript double ternary. I’d never heard of it before. MDN more aptly calls these “conditional chains”.

> const mammal = true
> const dog = false
> const animal = mammal ? dog ? 'shih tzu' : 'whale' : 'spotted wobbegong'
> animal
'whale'
> const mammal = false
> const animal = mammal ? dog ? 'shih tzu' : 'whale' : 'spotted wobbegong'
> animal
'spotted wobbegong'

I believe the proper way to format the above (to make it less horrible), would be

const animal = mammal
  ? dog // if mammal...
    ? 'shih tzu' // ...if dog then 'shih tzu'
    : 'whale' // else 'whale'
  : 'spotted wobbegong' // else 'spotted wobbegong'

Actually, it’s still pretty cruel and unusual. But the different branches would evaluate like this:

const mammal = true
const dog = true
const animal = mammal
  ? dog
    ? 'shih tzu'
    : 'whale'
  : 'spotted wobbegong'
console.log(animal) // 'shih tzu'
const mammal = true
const dog = false
const animal = mammal
  ? dog
    ? 'shih tzu'
    : 'whale'
  : 'spotted wobbegong'
console.log(animal) // 'whale'
const mammal = false
const dog = true
const animal = mammal
  ? dog
    ? 'shih tzu'
    : 'whale'
  : 'spotted wobbegong'
console.log(animal) // 'spotted wobbegong'
const mammal = false
const dog = false
const animal = mammal
  ? dog
    ? 'shih tzu'
    : 'whale'
  : 'spotted wobbegong'
console.log(animal) // 'spotted wobbegong'

MDN says ternary (“conditional”) chains are right-associative and Wikipedia says that means operations are grouped right to left. That’s a lot to ponder, but I think we’d expect this one to be grouped like this:

const animal = mammal ? ( dog ? 'shih tzu' : 'whale' ) : 'spotted wobbegong'