xxxxxxxxxx
condition ? expression1 : expression2
// Will return expression1 if condition = true and expression2 if condition != true
xxxxxxxxxx
//ternary operator example:
var isOpen = true; //try changing isOpen to false
var welcomeMessage = isOpen ? "We are open, come on in." : "Sorry, we are closed.";
xxxxxxxxxx
## Conditional (ternary) operator
#1 one condition
condition ? ifTrue : ifFalse;
#2 Multi conditions
condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
xxxxxxxxxx
//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"
xxxxxxxxxx
var variable;
if (condition)
variable = "something";
else
variable = "something else";
//is the same as:
var variable = condition ? "something" : "something else";
xxxxxxxxxx
// Write your function here:
const lifePhase = (age) => {
return age < 0 || age > 140 ? 'This is not a valid age':
age < 3 ? 'baby':
age < 13 ? 'child':
age < 20 ? 'teen':
age < 65 ? 'adult':'senior citizen';
}
console.log(lifePhase(5))
xxxxxxxxxx
condition ? exprIfTrue : exprIfFalse
////////////////////////////////////
//Example
const age = 26;
//set the bevarage conditionally depending on the age
const beverage = age >= 21 ? "You can have a Beer" : "Stick to Juice Kid";
console.log(beverage); //OUTPUT: "You can have a Beer"
//Same as
//if(age>=21){
//bevrage="You can have a Beer"}
//else{
//bevrage = "Stick to Juice Kid"}
xxxxxxxxxx
let amount = 50;
let food = amount > 100 ? 'buy coka-cola' : 'buy just a water bottle';
console.log(food)