Intern
What is a ternary operator?
sobes.tech AI
Answer from AI
The ternary operator (condition ? expression1 : expression2) is a shorthand form of the if-else conditional operator. It returns one of two values depending on the truthfulness of the condition.
Example of usage:
const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';
// status will be 'Adult'
This code is equivalent to the following:
const age = 20;
let status;
if (age >= 18) {
status = 'Adult';
} else {
status = 'Minor';
}
The ternary operator is convenient for simple conditional assignments and expressions, making the code more compact. However, for complex logic, if-else or switch are preferred.