Friday, August 20, 2021

The Conditional (Ternary) Operator in Javascript

Conditional Ternary Operator : In javascript instead of using if..else statement we can also use Ternary Operator inseat of i..else. Using this Conditional Operator we can write our code in one line.

Ternary operator is Expression so we can also use this in Template Literals

For Quick Decision we use Ternary Operators and For Big Statement checking multiple thing in logic building we use if..else

// Using Conditional Ternary Operator...

const age = 17;
age >= 18 ? console.log(`Condition is true`) : console.log(`Condition is not true`);

// This type we use in Our Programme..

const age = 18;
const ageCheck = age >= 18 ? 'True' : 'False';
console.log(ageCheck);

// When we use if..else instead of Ternary operator.

let myAge;
if (myAge >= 18) {
myAge = 'True';
} else {
myAge = 'False';
}
console.log(myAge);
// Using Template Literals for Ternary Operator..

let age = 18;
console.log(`I like to drink ${age >= 18 ? 'Wine' : 'Water'}`);

0 comments

Post a Comment