The ternary operator, also known as the conditional operator, is a shorthand way of writing an `if-else` statement in JavaScript. It has the following syntax:
condition ? expressionIfTrue : expressionIfFalse;
Here's how it works:
- If `condition` is true, the expression before the `:` (colon) is evaluated and returned.
- If `condition` is false, the expression after the `:` is evaluated and returned.
Here's an example:
let age = 20;// Using a ternary operator to determine if a person is eligible to votelet eligibility = age >= 18 ? "Eligible" : "Not eligible";console.log(eligibility); // Outputs: "Eligible"
In this example, the condition `age >= 18` is true, so the expression before the `:` ("Eligible") is evaluated and assigned to the variable `eligibility`.
You can also use the ternary operator for simple assignments or expressions within larger statements:
let isRaining = true;// Using a ternary operator to set the value of an alert messagelet alertMessage = isRaining ? "Bring an umbrella" : "Enjoy the weather";console.log(alertMessage); // Outputs: "Bring an umbrella"
It's important to use the ternary operator judiciously. While it's great for concise and simple conditional expressions, complex logic might be more readable with a traditional `if-else` statement.
Social Plugin