condition ? expression1 : expression2
Here, the “condition” is evaluated and if it is true, “expression1” is returned. If the condition is false, “expression2” is returned.
The ternary operator can be used in a variety of scenarios, such as assigning values, making decisions, or rendering dynamic content. Let’s see some examples to understand how it works.
- Assigning a value based on a condition:
let isLoggedIn = true;
let message = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(message);
In this example, if the variable isLoggedIn
is true, the value “Welcome back!” is assigned to the message
variable. Otherwise, the value “Please log in.” is assigned.
- Making a decision:
let score = 85;
let result = score >= 90 ? "Excellent" : "Good";
console.log(result);
Here, based on the value of the score
variable, the ternary operator determines whether the result is “Excellent” or “Good”.
- Rendering dynamic content (using it in JSX):
const isAuthenticated = true;
const message = <p>{isAuthenticated ? "User is logged in" : "User is not logged in"}</p>;
In this example, the content of the message
variable will be dynamically rendered based on the value of the isAuthenticated
variable. If the variable is true, it will display “User is logged in”, otherwise it will display “User is not logged in”.
The ternary operator is a powerful tool in JavaScript that allows for concise and readable code. However, it is important to use it judiciously and avoid nesting multiple ternary operators, as it can make the code less maintainable and harder to understand.