The ternary operator is a concise way to express conditional statements in programming languages.
Ternary Operator in Javascript
In javascript ternary operators typically looks like this:
1 | condition ? value_if_condition_is_true : value_if_condition_is_false |
- The
condition
is evaluated first. If it is true, the expression returns thevalue_if_condition_is_true
. - If the
condition
is false, the expression returns thevalue_if_condition_is_false
.
1 2 3 4 5 6 7 | const state = true; let result = (state === true) ? "passed" : "failed"; console.log(result); >>> passed |
In python we can use inline if blocks alternative to javascirpt-ternary operator.
Inline If Expression in Python
1 | x if condition else y |
In above, this expression returns “x” value if the condition is true, otherwise it returns to y
.
Here is a simple example:
1 2 3 4 5 6 7 | state: bool = True result = "passed" if state is True else "failed" print(result) >>> "passed" |
In above, we defined state variable that typed bool and we assigned True. To determine de result’s value, code blocks evaluates condition (if state is True) first if state is true, expression returns “passed”.
Simple Example of Inline If expressions
1 2 3 4 5 6 7 8 9 10 11 | def division(number_1: float, number_2: float) -> float: return number_1 / number_2 if number_2 != 0 else None print(division(10,2)) >>> 5 print(division(10,0)) >>> None |
There is a exampla that divide two number:
- if number_2 is not equal to 0 function returns division of number
- if number_2 is equal to zero function returns None.
Summary
Using ternary operators provides Conciseness, Code Performance, Reduced Nesting, Readability when they used correctly.