Ternary conditional operators in Python, Java, Javascript and PHP

Ternary conditional operators in Python, Java, Javascript and PHP

Pick between two outcomes using a condition. Ternary operators in Python, Java, Javascript and PHP


Ternary operators are used to choose between two values based on a condition. If the condition is true it returns one value, if false it will return the other.


Many different programming languages, for this tutorial we will learn how to use them in Java, Python, Javascript and PHP.


Ternary operator syntax in Java, Javascript and PHP is very similar if not identical.


Java


//basic syntax: (condition) ? value_if_true : value_if_false ;    
    
boolean conditionBool = false;    
int num1 = conditionBool ? 1 : 0 ;

In this ternary operator example we set the value of a boolean variable to false, thereby setting the value of num1 to 0 (the value if false)


Javascript


//basic syntax: (condition) ? value_if_true : value_if_false ;    
    
var conditionBool = false;    
var num1 = conditionBool ? 1 : 0 ;

The syntax for ternary operators in Javascript is identical to that of Java.


PHP


//basic syntax: (condition) ? value_if_true : value_if_false ;    
    
$conditionBool = false;    
$num1 = $conditionBool ? 1 : 0 ;

This also uses identical syntax.


Python


//basic syntax: value_if_true if (condition) else value_if_false    
    
conditionBool = False    
num1 = 1 if conditionBool else 0

The syntax here is quite different from the rest, but it performs the same function as in the other languages.


These can be useful to know in that they will save time and keep your code clean and easy to read compared to the alternative of using if else statements.



Christopher Thornton@Instructobit 7 years ago
or