Sobes.tech
Junior

What is a ternary operator in JavaScript?

sobes.tech AI

Answer from AI

The ternary operator (?:) in JavaScript is the only operator that takes three operands. It is a shorthand for the conditional if...else statement.

Syntax:

 condition ? expression_if_true : expression_if_false;

Where:

  • condition: An expression evaluated as true or false.
  • expression_if_true: The expression executed if condition is true.
  • expression_if_false: The expression executed if condition is false.

Example usage:

let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
// The variable status will contain the string "Adult"

Equivalent with if...else:

let age = 20;
let status;
if (age >= 18) {
    status = "Adult";
} else {
    status = "Minor";
}

The ternary operator is often used for assigning a value to a variable based on a condition or for returning a value from a function. It makes the code more concise but can reduce readability with overly complex conditions or expressions.