Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 453
user1354934 Avatar asked Apr 12 '17 03:04

user1354934


People also ask

How do you write a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What can I use instead of a ternary operator?

The alternative to the ternary operation is to use the && (AND) operation. Because the AND operator will short-circuit if the left-operand is falsey, it acts identically to the first part of the ternary operator.

How do you write an if else in ternary in C?

Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary. You can write the above program in just 3 lines of code using a ternary operator.


1 Answers

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; } 
like image 104
slebetman Avatar answered Sep 22 '22 17:09

slebetman