JavaScript ternary operator


The ternary operator in JavaScript is a shorthand way to perform a conditional operation. It provides a concise way to write simple if...else statements in a single line. The ternary operator takes three operands, which is why it is called "ternary."

Syntax

The syntax of the ternary operator is:

condition ? expressionIfTrue : expressionIfFalse;

How It Works

  1. Condition Evaluation: The condition is evaluated first.
  2. True Expression: If the condition is true, expressionIfTrue is evaluated and returned.
  3. False Expression: If the condition is false, expressionIfFalse is evaluated and returned.

Example

let age = 18; let canVote = age >= 18 ? 'Yes' : 'No'; console.log(canVote); // 'Yes'
  • Explanation:
    • The condition is age >= 18.
    • Since age is 18, the condition is true, so 'Yes' is assigned to canVote.
    • If age were less than 18, 'No' would be assigned to canVote.

Key Points

  1. Simple Conditional Expression: The ternary operator is ideal for simple conditions and expressions where you want to make the code more concise.

    let number = 10; let result = number % 2 === 0 ? 'Even' : 'Odd'; console.log(result); // 'Even'
  2. Nesting: You can nest ternary operators to handle multiple conditions, but it can reduce code readability if overused.

    let score = 85; let grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'D'; console.log(grade); // 'B'
    • Explanation:
      • This example uses nested ternary operators to determine the grade based on the score.
  3. Readability: While the ternary operator can make the code more concise, it can also make it harder to read if used with complex expressions or nested ternary operators. In such cases, using if...else statements may be more readable.

    let age = 22; let message = age >= 18 ? (age < 21 ? 'Young Adult' : 'Adult') : 'Minor'; console.log(message); // 'Adult'
    • Explanation:
      • This example uses a nested ternary operator to determine if the person is a 'Minor', 'Young Adult', or 'Adult' based on their age.
  4. Assignment: The ternary operator is often used in assignments to set values based on a condition.

    let isMember = true; let discount = isMember ? 0.1 : 0.05; console.log(discount); // 0.1
    • Explanation:
      • The discount is set to 0.1 if isMember is true; otherwise, it is set to 0.05.

Summary

  • Syntax: condition ? expressionIfTrue : expressionIfFalse;
  • Usage: Provides a concise way to handle simple conditional logic.
  • Nesting: Can be nested for more complex conditions but may impact readability.
  • Readability: Best used for straightforward conditions; for complex logic, if...else might be clearer.