ternary operators code example

Example 1: if statement shorthand c

if (true)
	printf("This is the shorthand");

// OR

(true) ? (/*run if true*/) : (/*run if false*/);

Example 2: ternary operator

(condition) ? (if true, do this) : (otherwise, do this)

Example 3: ternary operator

// (condition) ? (if true, do this) : (otherwise, do this)
const hasAccount = true
// let userDisplayMessage
// if (hasAccount) {
//   userDisplayMessage = 'Welcome Back'
// } else {
//   userDisplayMessage = 'Please Sign Up'
// }
const userDisplayMessage = hasAccount ? 'Welcome Back' : 'Please Sign Up'
console.log(userDisplayMessage)

Example 4: conditional operator

var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"

Example 5: javascript if shorthand

condition ? doThisIfTrue : doThisIfFalse

1 > 2 ? console.log(true) : console.log(false)
// returns false

Example 6: java ternary operator

Object myObject = booleanExpression ? valueIfTrue : valueIfFalse;

Tags:

Java Example