Q:

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

4
//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"
13
//ternary operator example:
var isOpen = true; //try changing isOpen to false
var welcomeMessage  = isOpen ? "We are open, come on in." : "Sorry, we are closed.";

16
var variable;
if (condition)
  variable = "something";
else
  variable = "something else";

//is the same as:

var variable = condition ? "something" : "something else";
1
function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

// Equivalent to:

function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}
3
condition ? exprIfTrue : exprIfFalse

//Example
let age = 26;
let beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"
-1
condition ? doThisIfTrue : doThisIfFalse

1 > 2 ? console.log(true) : console.log(false)
// returns false
0
var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"
-1
// 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)) 
0

New to Communities?

Join the community