JS Ternary functions with multiple conditions?

Yes you can go wild nesting ternaries. I find this version to be fairly readable:

var foo = (
  bar === 'a' ? 1 : // if 
  bar === 'b' ? 2 : // else if 
  bar === 'c' ? 3 : // else if
  null // else 
);

but that’s not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.

Leave a Comment