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.
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
1 function checkAge(age) {
2 return age > 18 ? 'Eligible' : 'Under age';
3 }
4
5 console.log(checkAge(20));
6 console.log(checkAge(10));
7 console.log(checkAge(18));
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.
1 Eligible
2 Under age
3 Under age
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.
1 Highest value among three is 20
Related options for your search