javascript ternary operator shorthand code example

Example 1: js ternary

condition ? ifTrue : ifFalse

Example 2: ternary operator shorthand javascript

let startingNum = startingNum ? otherNum : 1
// can be expressed as
let startingNum = otherNum || 1

// Another scenario not covered here is if you want the value 
// to return false when not matched. 
//The JavaScript shorthandfor this is:
let startingNum = startingNum ? otherNum : 0
// But it can be expressed as
let startingNum = startingNum && otherNum

Example 3: how to use ternary operator in javascript

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

Tags:

Php Example