Ternary Operator
The ternary operator, also known as the conditional operator, is a concise way to write an if-else
statement in a single line. It is often used for simple decision-making in cases where the logic involves assigning a value based on a condition. The syntax of the ternary operator is:
condition ? expressionIfTrue : expressionIfFalse;
Example:
Using Ternary Operator:
let isRaining = true;
let weather = isRaining ? "Bring an umbrella" : "No need for an umbrella";
console.log(weather); // Outputs: "Bring an umbrella"
Equivalent if-else
Statement:
let isRaining = true;
let weather;
if (isRaining) {
weather = "Bring an umbrella";
} else {
weather = "No need for an umbrella";
}
console.log(weather); // Outputs: "Bring an umbrella"
In both examples, the variable weather
is assigned a value based on the condition (isRaining
). The ternary operator provides a more concise and expressive way to achieve the same result in a single line.
Nested Ternary Operators:
You can also use nested ternary operators for more complex conditions, but it's important to maintain readability and not overuse them, as excessive nesting can reduce code clarity.
let isSunny = true;
let temperature = 25;
let activity =
isSunny
? temperature > 30
? "Go to the beach"
: "Go for a walk"
: "Stay indoors";
console.log(activity); // Outputs: "Go for a walk"
In this example, the nested ternary operator checks both if it's sunny and if the temperature is greater than 30, suggesting different activities based on the conditions.
While the ternary operator is a powerful tool for simplifying simple conditional assignments, it's essential to use it judiciously to maintain code readability. Complex logic may be better expressed using traditional if-else
statements.