Sobes.tech
Junior — Middle

Can you explain what a ternary operator in JavaScript is and how it is used?

sobes.tech AI

Answer from AI

The ternary operator in JavaScript is a shorthand form of the if...else conditional operator. It is written as:

condition ? expression_if_true : expression_if_false

If the condition is true, the first expression is returned; otherwise, the second.

Example:

const age = 18;
const canVote = age >= 18 ? 'Yes' : 'No';
console.log(canVote); // Outputs 'Yes'

The ternary operator is convenient for simple conditions and allows for more concise code.