JavaScript conditional (ternary) operator


The conditional (ternary) operator in JavaScript is a concise way to perform conditional logic. It’s a shorthand for an if-else statement and is often used to assign values based on a condition. The syntax is as follows:

condition ? expr1 : expr2

Breakdown:

  • condition: A boolean expression that evaluates to true or false.
  • expr1: The expression that is evaluated and returned if the condition is true.
  • expr2: The expression that is evaluated and returned if the condition is false.

How It Works:

  • If the condition is true, expr1 is returned.
  • If the condition is false, expr2 is returned.

Examples:

  1. Basic Example:

    let age = 18; let canVote = age >= 18 ? 'Yes' : 'No'; console.log(canVote); // 'Yes'

    In this example, age >= 18 is the condition. Since it evaluates to true, the result of the ternary operator is 'Yes'.

  2. Nested Ternary Operator:

    let score = 85; let grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'D'; console.log(grade); // 'B'

    Here, the ternary operator is nested to handle multiple conditions. It checks the score range and assigns the corresponding grade.

  3. Ternary Operator in Function Return:

    function getDiscount(isMember) { return isMember ? 0.1 : 0.05; } console.log(getDiscount(true)); // 0.1 console.log(getDiscount(false)); // 0.05

    The ternary operator returns a discount rate based on whether isMember is true or false.

  4. Using Ternary Operator for Inline Styling:

    let isDarkMode = true; let backgroundColor = isDarkMode ? 'black' : 'white'; console.log(backgroundColor); // 'black'

    Here, backgroundColor is set based on the isDarkMode boolean value.

Key Points:

  • Readability: While ternary operators are useful for concise conditional expressions, overusing or nesting them can make code harder to read. For more complex conditions, traditional if-else statements might be clearer.
  • Assignment: Ternary operators are commonly used to assign values based on conditions, which can make code more concise compared to using multiple if-else statements.