+ 1
How does the ternary operator work?
3 Réponses
+ 8
Ternary operator, or ternary expression, is similar to if-then-else statements. There can be small differences between programming languages.
It must have three parts:
- a condition
- a value when condition is true
- a value when condition is false
The main difference compared to if statements, is that you cannot use side effects (statements) inside the ternary expression, only values and expressions are allowed. Typically these are short and take only a single line. On the other hand, you can put longer code blocks in the 'then' and 'else' branches of an if statement.
In most languages, the structure is like this:
condition ? true_value : false_value
In Python they chose to spice it up a little bit:
true_value if condition else false_value
+ 2
ternary operator is like if/else statement but in smaller form
eg. int x = 10;
int y= 5;
x>y ? x : y
↑ ↑ ↑
Condition true false
0
Ternary operator is similar to an IF statement, but in a shorter version, and also being able to be in a single line, it works with 2 parts: "?" And ":"
The part before "?" Takes an evaluation expression (a condition), such as 5 > 4, the part after "?" is the operation when true, while the part after ":" is the operation when false, here is an example (javascript)
5 > 4 ? console.log("greater") : console.log("not greater");
The ternary operator can also be used while defining values of variables, for example
var myVar = 5 > 4 ? "value1" : "value2";
here we set the variable's value to a ternary operator, and the areas where the operators go use values instead without any kind of statement, this is an easy way to set variables based on a condition