Back to JavaScript
2026-05-037 min read

ternary operators (JavaScript)

Learn ternary operators (JavaScript) step by step with clear examples and exercises.

Lesson Title: Mastering JavaScript's Conditional (Ternary) Operator


Why This Matters

In this lesson, we will delve into the conditional (ternary) operator in JavaScript, a powerful tool that streamlines your code and enhances its readability. Understanding and mastering this operator is crucial for writing efficient, concise, and easy-to-understand JavaScript code. This knowledge can help you excel in coding interviews, real-world programming challenges, and even debugging complex issues in your projects.


Prerequisites

Before diving into the conditional (ternary) operator, it is essential to have a solid understanding of the following JavaScript concepts:

  1. Variables and data types
  2. Basic operators (arithmetic, comparison, logical)
  3. Control structures (if...else statements)
  4. Functions
  5. Understanding the concept of truthy and falsy values in JavaScript
  6. Familiarity with JavaScript's operator precedence and associativity
  7. Comprehension of common programming patterns such as loops, arrays, and objects

Core Concept

The conditional (ternary) operator is a shorthand for the if...else statement in JavaScript. It consists of three operands: a condition, a question mark (?), an expression to execute if the condition is true, a colon (:), and another expression to execute if the condition is false. The syntax is as follows:

condition ? expressionIfTrue : expressionIfFalse;

Let's break down this syntax:

  1. condition: This is any valid JavaScript expression that evaluates to a Boolean value (true or false).
  2. expressionIfTrue: This is the code block that gets executed if the condition is true.
  3. expressionIfFalse: This is the code block that gets executed if the condition is false.

Here's an example of using the conditional (ternary) operator to determine whether a number is even or odd:

let num = 5;
let result = num % 2 === 0 ? "Even" : "Odd";
console.log(result); // Output: "Odd"

In this example, we check if the remainder of num divided by 2 is equal to 0 (i.e., if num is even). If it is, we assign "Even" to the variable result. Otherwise, we assign "Odd". The conditional (ternary) operator allows us to write this logic in a single line of code, making it more concise and easier to read compared to using multiple lines with if...else statements.

Using Multiple Assignments

One advantage of the ternary operator is that you can perform multiple assignments within the same statement:

let num = 5;
let evenOrOdd, isEven;
isEven = (num % 2 === 0);
evenOrOdd = isEven ? "Even" : "Odd";
console.log(evenOrOdd); // Output: "Odd"

In this example, we first check if num is even and store the result in the variable isEven. Then, we use the conditional (ternary) operator to determine whether evenOrOdd should be set to "Even" or "Odd", based on the value of isEven.

Nested Ternary Operators

While it is possible to nest ternary operators, it's generally considered bad practice due to readability concerns:

// Avoid nested ternary operators
let num = 5;
let result = (num > 10) ? "Greater than 10" : (num === 5) ? "Five" : "Less than or equal to 10";
console.log(result); // Output: "Five"

In this example, the nested ternary operator makes the code harder to read and understand. It's better to break it down into multiple if...else statements or use a single ternary operator:

let num = 5;
let result;
if (num > 10) {
result = "Greater than 10";
} else if (num === 5) {
result = "Five";
} else {
result = "Less than or equal to 10";
}
console.log(result); // Output: "Five"

Worked Example

Let's write a function that calculates the fee based on whether a person is a member or not and their age:

function calculateFee(isMember, age) {
return isMember ? (age < 18 ? "$0.00" : (age <= 64 ? "$2.00" : "$5.00")) : (age >= 65 ? "$0.00" : "$10.00");
}

console.log(calculateFee(true, 20)); // Output: "$2.00"
console.log(calculateFee(false, 30)); // Output: "$10.00"
console.log(calculateFee(true, 15)); // Output: "$0.00"
console.log(calculateFee(false, 67)); // Output: "$0.00"

In this example, we define a function calculateFee that takes two arguments, isMember and age. Inside the function, we use the conditional (ternary) operator to determine whether the fee is $2.00, $5.00, or $10.00 based on the values of isMember and age. If isMember is true, the fee depends on the age: $0.00 for people under 18, $2.00 for people between 18 and 64, and $5.00 for people over 64. If isMember is false, the fee is $10.00 unless the person is over 65, in which case the fee is $0.00.


Common Mistakes

  1. Forgetting to enclose the entire conditional (ternary) operator in parentheses:
// Incorrect
let result = num > 10 ? "Greater than 10" : "Less than or equal to 10";

// Correct
let result = (num > 10) ? "Greater than 10" : "Less than or equal to 10";
  1. Using the conditional (ternary) operator when an if...else statement would be more appropriate:
// Incorrect use of ternary operator
let num = 5;
let result = num > 10 ? "Greater than 10" : "Less than or equal to 10";
if (result === "Greater than 10") {
console.log("The number is indeed greater than 10.");
} else {
console.log("The number is not greater than 10.");
}

In this example, the conditional (ternary) operator can be replaced with a simpler if...else statement to achieve the same result. It's essential to use the appropriate control structure for your specific needs.

Nested Ternary Operators

While it is possible to nest ternary operators, it's generally considered bad practice due to readability concerns:

// Avoid nested ternary operators
let num = 5;
let result = (num > 10) ? "Greater than 10" : (num === 5) ? "Five" : "Less than or equal to 10";
console.log(result); // Output: "Five"

In this example, the nested ternary operator makes the code harder to read and understand. It's better to break it down into multiple if...else statements or use a single ternary operator:

let num = 5;
let result;
if (num > 10) {
result = "Greater than 10";
} else if (num === 5) {
result = "Five";
} else {
result = "Less than or equal to 10";
}
console.log(result); // Output: "Five"

Practice Questions

  1. Write a JavaScript function that checks whether a given year is a leap year using the conditional (ternary) operator.
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

console.log(isLeapYear(2000)); // Output: true
console.log(isLeapYear(1900)); // Output: false
  1. Implement a function that calculates the maximum of three numbers using the conditional (ternary) operator.
function maxOfThree(num1, num2, num3) {
return Math.max(num1, num2, num3);
}

console.log(maxOfThree(5, 10, 15)); // Output: 15
  1. Create a function that determines whether a number is prime or composite using the conditional (ternary) operator.
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i < num; i++) {
if (num % i === 0) return false;
}
return true;
}

console.log(isPrime(5)); // Output: true
console.log(isPrime(6)); // Output: false

FAQ

Q: Can I use multiple conditions in a single conditional (ternary) operator?

A: No, you cannot. The conditional (ternary) operator only allows for a single condition at a time. If you need to check multiple conditions, consider using if...else statements instead.

Q: Is it bad practice to use the conditional (ternary) operator excessively in my code?

A: Not necessarily. The conditional (ternary) operator can help make your code more concise and easier to read when used appropriately. However, overusing it may lead to less-readable code, so it's essential to find the right balance between brevity and clarity.

Q: Can I assign a variable inside the conditional (ternary) operator?

A: Yes, you can assign a variable inside the conditional (ternary) operator by using multiple assignments as shown in the "Core Concept" section. However, it's generally considered better practice to declare and initialize variables outside of the ternary operator for clarity and readability.

Q: Can I use the conditional (ternary) operator in a for loop or while loop?

A: No, you cannot directly use the conditional (ternary) operator in a for loop or while loop. However, you can use it within the loop's condition or body to make decisions based on loop iterations.

Q: Can I use the conditional (ternary) operator with arrays?

A: Yes, you can use the conditional (ternary) operator with arrays by applying it to each element of the array using a for loop, Array.map(), or other array manipulation functions. However, it's essential to be mindful of readability and maintainability when working with complex data structures.

Q: Can I use the conditional (ternary) operator with objects?

A: Yes, you can use the conditional (ternary) operator with objects by accessing properties or updating values within an object using dot notation or bracket notation. However, it's essential to be mindful of readability and maintainability when working with complex data structures.

ternary operators (JavaScript) | JavaScript | XQA Learn