In this tutorial, you will be going learn the javascript ternary operator and Examples
There are two ways to write conditional operators the regular one is the if/else statement and another switch statement
But there is another conditional operator it is a very nice and easy single-line conditional operator.
There is javascript ternary operator is the only javascript operator takes the three operands : and followed by a Question mark.
It works like an if/else statement and the ternary operator evaluates a condition and executes a block of code.
syntax:
condition? expression1: expression 2;
How does the javascript ternary operator work?
The ternary operator are want to execute the block of code. If the expression is executed the condition is true followed by the question mark and followed by a colon: expression executed the condition is false.
condition? True: False;
This example shows a message that a person can vote for the election if the age is greater than or equal to 18.
const age =18;
let msg;
age >= 20 ? (msg = "you are eligible for vote") : (msg = ' you are not eligible for election);
console.log (msg);
you can use the ternary operator same as below code also :
const age =18;
let msg;
msg = age >=16 ? 'you are eligible for voting :
'you are not eligible for voting';
console.log(msg);
If the condition is true, the first expression is executes. If it is false the second expression is follow to executes.
I hope you will learn javascript ternary operator and follow the above codes and to make the simple and actually understand how the conditional works.