HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Ternary Operator

The ternary operator (also called the conditional operator) is the only JavaScript operator that takes three operands. It is frequently used as a shorthand for an if...else statement.


The Syntax

The syntax for the ternary operator involves a question mark ? and a colon :.

condition ? expressionIfTrue : expressionIfFalse;

How it works:

  • First, the condition is evaluated.
  • If the condition is true, the expression after the ? is executed.
  • If the condition is false, the expression after the : is executed.

Comparison: If...Else vs. Ternary

Imagine you want to check if a user is old enough to vote. Here is how you would do it in both ways:

Using If...Else:

let age = 20;
let voteable;

if (age >= 18) {
    voteable = "Yes";
} else {
    voteable = "No";
}

console.log(voteable); // "Yes"

Using Ternary Operator:

let age = 20;
let voteable = (age >= 18) ? "Yes" : "No";

console.log(voteable); // "Yes"
Tip: The ternary operator makes your code much shorter and is perfect for assigning a value to a variable based on a simple condition.

Handling Multiple Outcomes

While possible, you can "nest" ternary operators to handle more than two outcomes. However, this can become difficult to read very quickly.

let time = 10;
let greeting = (time < 12) ? "Good morning" : (time < 18) ? "Good afternoon" : "Good evening";

console.log(greeting); // "Good morning"
Warning: Clean code is better than short code. If your ternary operator spans multiple lines or becomes hard to understand, it is better to use a standard if...else if...else block.

Common Use Case: Null Checks

The ternary operator is often used to provide a default value if data is missing:

let userName = null;
let display = userName ? userName : "Guest";

console.log(display); // "Guest"

Key Points to Remember

  • The ternary operator uses ? and : to make decisions
  • It is called "ternary" because it takes three operands
  • It is a concise alternative to if...else for simple logic
  • Use it to make your code cleaner, but avoid over-nesting for readability