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...
Use a helper function:
Now your code is very readable, and there's no repetition.
The hierarchy of coding concerns is:
All the answers on the page so far appear to be correct, but I think my version has the highest clarity, which is more important than conciseness. If you don't count the helper function—as it can be reused—it is the most concise as well. The somewhat similar suggestion to use a helper function unfortunately uses a lambda that, to me, just obscures what it's doing. A simpler function with one purpose that doesn't take a lambda, just values, is to me much better.
P.S. If you like ES6 syntax:
You could use re-assignment:
&&
operator for reassignment, because if the first condition is false, the second expression won't be evaluatedEx.
This is a simple solution with bitwise NOT and a default value of
-1
which results later to zero.It works basically with a double bitwise NOT, which returns the original value or a default value, which after applying bitwise NOT returns zero.
Let's have a look to the table of truth:
Use an extract variable refactoring:
It is even better with
const
instead ofvar
. You could also do an additional extraction:In practice, use more meaningful names than
index
,condition
, andvalue
.Personally I find the best way to do this is still the good old
if
statement: