ternary (Conditional) operator in Javascript
The ternary operator is a conditional operator that allows to write conditional and default option in single statement. A ternary operator is an alternative for using if-else and nested if-else statements. The order of execution for this operator is from left to right.
Syntax
 1 <condition> ? <exprIfTrue> : <exprIfFalse>
condition : An expression which returns boolean value
expIfTrue : An expression which needs to be executed if condition returns true
exprIfFalse : An expression which needs to be executed if condition returns false
Ternary operator
 1 function checkAge(age) {
 2    return age > 18 ? 'Eligible' : 'Under age';
 3 }
 4 
 5 console.log(checkAge(20)); // prints Eligible
 6 console.log(checkAge(10)); // prints Under age
 7 console.log(checkAge(18)); // prints Under age
In the above example, a function checkAge() is define which accepts age value. It validate whether age greater than 18 returns Eligible or under age. A function is called by specifying 20, 10, 18 which will returns string based on specified value after validating using ternary operator.
Output
 1 Eligible
 2 Under age
 3 Under age

Nested ternary operator

Nested ternary operator
 1 const a = 10;
 2 const b = 5;
 3 const c = 20;
 4 
 5 const value = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
 6 
 7 console.log(`Highest value among three is ${value}`);
In the above example, a three variables are define and initialized with values. A maximum amount three is determine using nested ternary operator. A resulting value is assigned to the variable and print maximum amount all variable.
Output
 1 Highest value among three is 20
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us