The ternary operator has three parts:
- A condition: This is the expression to be evaluated as true or false.
- A question mark (?) separates the condition from the following expressions.
- A colon separates two expressions (:): The first expression will be executed if the condition is true, and the second expression will be executed if the condition is false.
condition ? expressionIfTrue : expressionIfFalse;
const age = 18; const canVote = age >= 18 ? 'Yes, you can vote.' : 'No, you cannot vote.'; console.log(canVote);
Yes, you can vote.
In the above code example, the condition age >= 18 is evaluated.
If true, the canVote variable is assigned ‘Yes, you can vote.’
If false, the canVote variable is assigned ‘No, you cannot vote’.
The output of the “console.log()” statement is ‘Yes, you can vote.’, as the condition age >= 18 is true.
The ternary operator is helpful for simple conditional assignments or expressions to keep your code concise and readable.
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.