Conditional Operator[]
Formally known as a Ternary operator, this is a shorthand way of including a conditional statement in a single line of code. It achieves the same effect as tradiitonal if/else logic, but is shorter and more confusing.
Operator Syntax | Description | Example ( x=3 ) | Result |
---|---|---|---|
var = (condition)? true_result : false result ; | Assigns a variable based on conditions | myHello = (user == "Mom")? "Hello Mom!" : "Hello World" ; | "Hello World" (mom will never ready this) |
Pseudocode:[]
if(user == "Mom"){
- return "Hello Mom!";
}else{
- return "Hello World";
}
Better pseudocode:[]
returnValue;
if(user == "Mom"){
- returnValue = "Hello Mom!";
}else{
- returnValue = "Hello World";
}
return returnValue;