How does the ternary operator work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How does the ternary operator work?

2nd Sep 2023, 4:37 AM
Jai
3 Answers
+ 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
2nd Sep 2023, 4:59 AM
Tibor Santa
Tibor Santa - avatar
+ 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
2nd Sep 2023, 9:43 AM
Alhaaz
Alhaaz - avatar
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
3rd Sep 2023, 4:34 PM
Nest Admiral
Nest Admiral - avatar