if/else statement. The syntax for a ternary operator is as follows:
condition ? expression1 : expression2
The condition is evaluated, and if it’s true, the expression
expression1 is executed, and if it’s false,
expression2 is executed.
let x = 10; let result = (x > 5) ? "x is greater than 5" : "x is less than or equal to 5"; console.log(result);
In this example, the ternary operator is used to assign the value of
result based on the result of the condition
x > 5. If
x is greater than
5, the message “x is greater than 5” is assigned to
result, and if
x is less than or equal to
5, the message “x is less than or equal to 5” is assigned to
result. The value of
result is then logged to the console.
Ternary operators can be a useful shorthand way of writing simple
if/else statements in your code, but it’s important to use them sparingly and not overuse them, as they can make your code more difficult to read and understand.