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...
I think the
||
operator can be tailored toindexOf
:The returned value is shifted up by 1, making 0 from -1, which is falsey and therefore gets replaced by the second 1. Then it is shifted back.
However, please keep in mind that readability is superior to avoiding repetition.
Not really, just use another variable.
Your example generalizes to something like this.
You're testing a computed value, then assigning that value to a variable if it passes some predicate. The way to avoid re-calculating the computed value is obvious: use a variable to store the result.
I get what you mean - it seems like there ought to be some way to do this that looks a little cleaner. But I think that's the best way (idiomatically) to do this. If you were repeating this pattern a lot in your code for some reason, you might write a little helper function:
I personally prefer two variants:
Pure if, like @slebetman suggested
Separate function, which replaces invalid value with default one, like in this example:
A ternary is like an if-else, if you don't need the else part, why not just a single if instead..
For numbers
You can use the
Math.max()
function.It will keep the boundaries of the result from
0
until the first result greater than0
if that's the case. And if the result fromindexOf
is-1
it will return 0 as is greater than-1
.For booleans and boolean-y values
For JS there is no general rule AFAIK specially because how falsy values are evaluated.
But if something can help you most of the time is the or operator (
||
):You have to be very careful with this, because in your first example,
indexOf
can return0
and if you evaluate0 || -1
it will return-1
because0
is a falsy value.You're probably looking for a coalescing operator. Luckily, we can leverage the
Array
prototype to create one:This could be further generalized to your case, by adding a parameter to the function: