The ternary operator in JavaScript is a shorthand way of writing conditional statements. It is also known as the conditional operator and is represented by the ? and : symbols.
The basic syntax for using the ternary operator is:
condition ? expression1 : expression2;
In this example, the condition is evaluated. If the condition is true, the first expression is executed; otherwise, the second expression is executed.
Here are some simple examples of using the ternary operator in JavaScript.
Example: Check Age
const age = 18;
const isAdult = (age >= 18) ? "Adult" : "Minor";
console.log(isAdult); // Output: Adult
This example demonstrates how to use the ternary operator to check if a person is an adult based on their age.
const x = 10;
const y = (x > 5) ? 100 : 200;
console.log(y); // Output: 100
This example shows how to use the ternary operator to assign a value based on a condition.
Ternary operators can be nested to handle multiple conditions. However, it is recommended to avoid excessive nesting for readability.
Example: Grade Classification
const score = 85;
const grade = (score >= 90) ? 'A' :
(score >= 80) ? 'B' :
(score >= 70) ? 'C' :
(score >= 60) ? 'D' : 'F';
console.log(grade); // Output: B
This example demonstrates how to classify a student's grade based on their score using nested ternary operators.
The ternary operator can be used to return different values from a function based on a condition.
Example: Check Positive or Negative
function checkNumber(num) {
return (num >= 0) ? "Positive" : "Negative";
}
console.log(checkNumber(5)); // Output: Positive
console.log(checkNumber(-3)); // Output: Negative
This example shows how to use the ternary operator to return "Positive" or "Negative" based on the input number.
Here are some important notes and best practices when using the ternary operator in JavaScript:
The ternary operator provides a concise way to write conditional statements in JavaScript. By understanding its syntax and usage, you can write more efficient and readable code.