Conditional Ternary Operator in JavaScript
1. Purpose
- The ternary operator is a concise way to express a simple if…else statement in a single line.
2. Syntax
condition ? expressionIfTrue : expressionIfFalse;
- condition: An expression that evaluates to true or false.
- ? If the condition is true, the expression after the ? is executed.
- : If the condition is false, the expression after the : is executed.
3. Example:
let age = 25;
let isAdult = (age >= 18) ? "Adult" : "Minor";
console.log(isAdult); // Output: "Adult"
In this example, age >= 18 is the condition.
- If age is greater than or equal to 18, the value of isAdult will be “Adult”.
- If age is less than 18, the value of isAdult will be “Minor”.