ternary operator for 3 conditions in javascript code example

Example 1: ternary operator javascript

// ternary operators are frequently used as a shorter cleaner if statement
// condition ? exprIfTrue : exprIfFalse

let age = 15;
let canDrive = age >= 16 ? 'yes' : 'no';
// canDrive will be 'no'
// the condition will be age > 16 which is false so canDrive will equal exprIfFalse

// this ternary is the same as this if else statement
let age = 15;
let canDrive;
if (age >= 16) {
    canDrive = 'yes';
} else {
    canDrive = 'no';
}

// canDrive will be 'no' because 15 is less than 16

Example 2: multiple ternary operator javascript

var icon = (area == 1) ? icon1 : (area == 2) ? icon2 : icon0;

Example 3: examples of Conditional Operator js

var age = 19;
var canDrive = age > 16 ? 'yes' : 'no';

Example 4: ternary operator if javascript

condition ? exprIfTrue : exprIfFalse

Tags:

Misc Example