js when to use ternary operator code example

Example 1: js ternary

condition ? ifTrue : ifFalse

Example 2: javascript ternary operator

//ternary operator syntax and usage:
condition ? doThisIfTrue : doThisIfFalse

//Simple example:
let num1 = 1;
let num2 = 2;
num1 < num2 ? console.log("True") : console.log("False");
// => "True"

//Reverse it with greater than ( > ):
num1 > num2 ? console.log("True") : console.log("False");
// => "False"

Example 3: 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

Tags:

Misc Example