The JavaScript ternary operator is a shorthand for the if-else
statement. It evaluates a condition and returns one of two values based on whether the condition is true or false. The syntax of the ternary operator is:
condition ? valueIfTrue : valueIfFalse
Example of Using the Ternary Operator with Functions
Below is an example where we use the ternary operator to conditionally return different results based on a function’s input.
Example: Checking Age for Voting Eligibility
Let’s write a function that checks if a person is eligible to vote. We’ll use the ternary operator to decide the message based on the age.
function checkEligibility(age) {
return age >= 18 ? "You are eligible to vote!" : "Sorry, you are not eligible to vote.";
}
console.log(checkEligibility(20)); // Output: "You are eligible to vote!"
console.log(checkEligibility(16)); // Output: "Sorry, you are not eligible to vote."
Explanation:
- The function
checkEligibility(age)
takes anage
as an argument. - The ternary operator checks if the
age
is greater than or equal to 18.- If the condition is true (age >= 18), it returns
"You are eligible to vote!"
. - If the condition is false, it returns
"Sorry, you are not eligible to vote."
.
- If the condition is true (age >= 18), it returns
Another Example: Greeting a User Based on Time of Day
Let’s create a function that greets the user depending on the time of day (morning, afternoon, or evening).
function greetUser(hour) {
return hour < 12
? "Good Morning!"
: hour < 18
? "Good Afternoon!"
: "Good Evening!";
}
console.log(greetUser(9)); // Output: "Good Morning!"
console.log(greetUser(14)); // Output: "Good Afternoon!"
console.log(greetUser(20)); // Output: "Good Evening!"
Explanation:
- The function
greetUser(hour)
uses nested ternary operators. - The first condition checks if the hour is less than 12 (morning).
- If it’s not, the second condition checks if the hour is less than 18 (afternoon).
- If neither condition is true, it assumes it’s evening.
Benefits of Using the Ternary Operator
- Conciseness: The ternary operator provides a compact way to write simple conditional logic.
- Readability: It is easier to read for short conditions compared to writing multiple
if-else
statements.
However, for more complex conditions or when you need multiple statements in each branch, traditional if-else
blocks might be clearer.
Let me know if you’d like more examples or clarifications!