How to write a ternary operator (aka if) expression without repeating yourself

user1354934 picture user1354934 · Apr 12, 2017 · Viewed 17.6k times · Source

For example, something like this:

var value = someArray.indexOf(3) !== -1 ? someArray.indexOf(3) : 0

Is there a better way to write that? Again, I am not seeking an answer to the exact question above, just an example of when you might have repeated operands in ternary operator expressions...

Answer

slebetman picture slebetman · Apr 12, 2017

Personally I find the best way to do this is still the good old if statement:

var value = someArray.indexOf(3);
if (value === -1) {
  value = 0;
}