Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Ternary Operator

Learn how to use the ternary operator to evaluate conditions and select values using a short, readable expression in TypeScript.

Simple Explanation: The ternary operator is a short alternative to a simple if/else statement. It checks a condition and chooses one of two expressions based on the result.

What Will We Learn?

The ternary operator is useful when a value needs to be selected based on a condition.

  • Understand the ternary operator syntax.
  • Evaluate true and false conditions.
  • Compare ternary expressions with if/else statements.
  • Use ternary operators with strings and numbers.
  • Combine conditions with the ternary operator.
  • Apply ternary operators in practical applications.

Ternary Operator Workflow

Follow these steps to understand how a ternary expression selects a result.

📥
Step 1
Check Condition

Evaluate a condition.

→
⚖️
Step 2
Evaluate Result

Determine true or false.

→
🔀
Step 3
Select Expression

Choose the matching expression.

→
✅
Step 4
Get Result

Store or display the value.

1. Ternary Operator Syntax

The ternary operator uses three parts: a condition, an expression for the true case, and an expression for the false case.

Syntax

condition ? valueIfTrue : valueIfFalse;

How It Works

  • The condition is evaluated first.
  • If the condition is true, the expression before the colon is selected.
  • If the condition is false, the expression after the colon is selected.

Simple Example

let age: number = 20;

let result = age >= 18 ? "Adult" : "Minor";

console.log(result);

Expected Output

Adult

The condition age >= 18 is true, so the expression selects "Adult".

2. Ternary Operator with Numbers

You can use a ternary expression to select a numeric value based on a condition.

Example

let marks: number = 75;

let bonusMarks = marks >= 70 ? 10 : 0;

console.log("Marks: " + marks);
console.log("Bonus Marks: " + bonusMarks);

Expected Output

Marks: 75
Bonus Marks: 10

Since the marks are at least 70, the program selects the value 10. Otherwise, it selects 0.

3. Ternary Operator with Strings

A ternary operator can choose between different text messages according to a condition.

Example

let isLoggedIn: boolean = true;

let message = isLoggedIn
    ? "Welcome Back"
    : "Please Login";

console.log(message);

Expected Output

Welcome Back

The condition is true, so the program selects "Welcome Back". When isLoggedIn is false, the output becomes "Please Login".

4. Ternary Operator vs if/else

Both approaches can select a result based on a condition. The ternary operator is useful for simple expressions, while if/else is often clearer for multiple statements or complex logic.

Using if/else

let marks: number = 80;
let result: string;

if (marks >= 35) {
    result = "Pass";
} else {
    result = "Fail";
}

console.log(result);

Using Ternary Operator

let marks: number = 80;

let result = marks >= 35 ? "Pass" : "Fail";

console.log(result);

Expected Output for Both

Pass
Feature Ternary Operator if/else
Syntax Short expression Statement blocks
Common use Selecting one of two values Executing different blocks of code
Multiple operations Can become hard to read Usually clearer
Result Produces a value Executes the selected statement block

5. Ternary with Comparison Operators

Comparison operators can be used inside the ternary condition to check values such as marks, age, and fees.

Example

let courseFees: number = 30000;
let studentBudget: number = 35000;

let status = courseFees <= studentBudget
    ? "Within Budget"
    : "Over Budget";

console.log(status);

Expected Output

Within Budget

Since the course fees do not exceed the student's budget, the expression selects "Within Budget".

6. Nested Ternary Operator

A nested ternary places one ternary expression inside another. It can select from more than two possible results, but should be used carefully to keep code readable.

Example

let marks: number = 75;

let grade = marks >= 90
    ? "A"
    : marks >= 70
        ? "B"
        : marks >= 35
            ? "C"
            : "Fail";

console.log("Grade: " + grade);

Expected Output

Grade: B

The marks are below 90 but at least 70, so the expression selects grade B.

Best Practice: Nested ternary expressions can become difficult to follow. For many conditions, an if/else if/else statement may be easier to maintain.

7. Ternary Operator with Functions

A ternary expression can choose which function to call based on a condition.

Example

function showSuccess(): string {
    return "Registration Successful";
}

function showFailure(): string {
    return "Registration Failed";
}

let isRegistered: boolean = true;

let message = isRegistered
    ? showSuccess()
    : showFailure();

console.log(message);

Expected Output

Registration Successful

When isRegistered is true, showSuccess() is called. Otherwise, showFailure() is called.

8. Type Inference in Ternary Expressions

TypeScript can infer the result type of a ternary expression from the two possible result expressions.

Example

let isEligible: boolean = true;

let result = isEligible ? "Eligible" : "Not Eligible";

console.log(result);

Expected Output

Eligible

In this example, both possible values are strings, so TypeScript infers result as a string.

Practical Example: CIIT Course Admission

Let's use ternary operators to display course admission and payment messages.

Example

let studentName: string = "Priya";
let marks: number = 75;
let courseFees: number = 30000;
let studentBudget: number = 35000;
let feesPaid: boolean = false;

let result = marks >= 35 ? "Passed" : "Failed";

let budgetStatus = courseFees <= studentBudget
    ? "Within Budget"
    : "Over Budget";

let paymentStatus = feesPaid
    ? "Payment Completed"
    : "Payment Pending";

console.log("Student: " + studentName);
console.log("Result: " + result);
console.log("Budget: " + budgetStatus);
console.log("Payment: " + paymentStatus);

Expected Output

Student: Priya
Result: Passed
Budget: Within Budget
Payment: Payment Pending

The program checks the student's marks, compares course fees with the available budget, and chooses an appropriate payment message.

Common Mistakes

  • Forgetting the colon between the true and false expressions.
  • Writing a condition that does not return the intended result.
  • Using nested ternaries that are difficult to understand.
  • Assuming the ternary operator executes both branches.
  • Returning incompatible values from the two branches without considering the resulting type.
Tip: Use ternary expressions for simple value selection. Prefer if/else statements when multiple operations or complex decision-making are involved.

Practice Task

Create a TypeScript program for a student applying to a course at CIIT Training Institute.

  • Student marks: 82
  • Passing marks: 35
  • Course fees: 30000
  • Student budget: 25000
  • Fees paid: true

Use ternary expressions to determine the result, budget status, and payment status.

Hint

let marks = 82;
let passingMarks = 35;

let courseFees = 30000;
let studentBudget = 25000;

let feesPaid = true;

let result = marks >= passingMarks ? "Pass" : "Fail";

let budgetStatus = courseFees <= studentBudget
    ? "Within Budget"
    : "Over Budget";

let paymentStatus = feesPaid
    ? "Paid"
    : "Pending";

console.log(result);
console.log(budgetStatus);
console.log(paymentStatus);

Expected Output

Pass
Over Budget
Paid

Summary

In this lesson, we learned how to use the ternary operator to select values based on conditions. We covered its syntax, comparison conditions, nested expressions, function calls, and practical course admission examples.

Key Point: The ternary operator uses the format condition ? valueIfTrue : valueIfFalse. Use it for simple decisions and prefer if/else when the logic becomes complex.