Ternary conditional operator code example

Example 1: ternary operator

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

Example 2: javascript if shorthand

condition ? doThisIfTrue : doThisIfFalse

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

Example 3: javascript ternary operator

//ternary operator example:
var isOpen = true; //try changing isOpen to false
var welcomeMessage  = isOpen ? "We are open, come on in." : "Sorry, we are closed.";

Example 4: ternary operator in javascript

FullName: (obj.FirstName && obj.LastName) ? obj.FirstName + " " + obj.LastName : "missing values",

Example 5: ternary operator

isMember ? '$2.00' : '$10.00'
// isMember true =>  output: "$2.00"

// isMember false =>  output: "$10.00"

// isMember null =>  output: "$10.00"

Example 6: The conditional (ternary) operator with three condition

String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior";

Tags:

Php Example