Home > front end >  Convert if else statement into ternary multiple lines
Convert if else statement into ternary multiple lines

Time:04-30

I'm confused with the question mark and the colon on ternary can someone explain how to do it correctly

const bill = 220;
const fifty = 50;
const oneHundred = 100;
const twoHundred = 200;

if(bill < fifty)
    console.log(`(A) bill is less than 50`);
else if(bill < oneHundred)
    console.log('(B) bill is greater than 50');
else if(bill < twoHundred)
    console.log('(C) bill is greater than 100');
else if(bill > twoHundred)
    console.log('(D) bill is greater than 200');

CodePudding user response:

if you want to use ternary instead if-else here your answer:

const bill = 220;
const fifty = 50;
const oneHundred = 100;
const twoHundred = 200;

bill < fifty ? console.log(`(A) bill is less than 50`) : bill < oneHundred ? console.log('(B) bill is greater than 50') : bill < twoHundred ? console.log('(C) bill is greater than 100') : console.log('(D) bill is greater than 200');

CodePudding user response:

Conditional (ternary) operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if...else statement.

const bill = 220;
const fifty = 50;
const oneHundred = 100;
const twoHundred = 200;

console.log(
  bill < fifty
    ? "(A) bill is less than 50"
    : bill < oneHundred
    ? "(B) bill is greater than 50"
    : bill < twoHundred
    ? "(C) bill is greater than 100"
    : "(D) bill is greater than 200"
);

CodePudding user response:

You could get a message from a ternary operator.

For better reading (and understanding) the expression is nested for the levels.

const
    bill = 220,
    fifty = 50,
    oneHundred = 100,
    twoHundred = 200,
    message = bill < fifty
        ? '(A) bill is less than 50'
        : bill < oneHundred
            ? '(B) bill is greater than 50'
            : bill < twoHundred
                ? '(C) bill is greater than 100'
                : bill > twoHundred
                ? '(D) bill is greater than 200'
                : '';

console.log(message);

CodePudding user response:

The simple way to explain are see with this form

condition ? (if condition == true) : (if condition == false)

Other thing you neet to now are the ternary "return" the data depending of the condition

let age = 30
let message = age > 18 ? "Can pass" : "Can't pass"
console.log(message) // Output: Can pass
  • Related