How do you use the conditional (ternary) operator to check multiple conditions in JavaScript?

In JavaScript, the conditional operator, often referred to as the ternary operator, allows you to write a concise form of an `if...else` statement. It's a shorthand way of expressing a conditional check with a single line of code. The syntax of the ternary operator is:


condition ? expressionIfTrue : expressionIfFalse;


Here's an example that demonstrates how to use the ternary operator to check multiple conditions:

let age = 25;
let canVote = (age >= 18) ? "Yes, can vote" : "No, cannot vote";

console.log(canVote);  // Outputs: "Yes, can vote"

In this example:
- The condition is `age >= 18`.
- If the condition is `true`, the expression ` "Yes, can vote"` is executed.
- If the condition is `false`, the expression `"No, cannot vote"` is executed.

The result is assigned to the variable `canVote`.

You can also chain multiple ternary operators to check multiple conditions. However, keep in mind that using too many nested ternary operators can lead to less readable code, so it's essential to strike a balance between conciseness and readability.

Here's an example with multiple conditions:

let weather = "sunny";
let temperature = 25;

let activity = (weather === "sunny") 
    ? (temperature > 20) ? "Go to the beach" : "Go for a walk"
    : "Stay indoors";

console.log(activity);  // Outputs: "Go to the beach"


In this example, the first ternary operator checks if the weather is "sunny". If true, it checks the temperature, and based on that, it suggests an activity.

The ternary operator is a powerful tool for expressing conditional logic concisely, but it's crucial to use it judiciously to maintain code readability. For complex conditions, using a regular `if...else` statement might be more appropriate.