Your Page Title
🔍

    ES6 Ternary Operator

    The ternary operator is a short and powerful way to write conditional statements in JavaScript. Introduced in ES6 (ECMAScript 2015), it helps you write cleaner and more readable code, especially when you’re checking a simple condition and returning one of two values.


    Syntax of the Ternary Operator

     condition ? expressionIfTrue : expressionIfFalse;
    • condition: A boolean expression (true or false)
    • expressionIfTrue: Runs if the condition is true
    • expressionIfFalse: Runs if the condition is false

    It’s called “ternary” because it involves three parts.


    Example: Traditional if...else

    let age = 18;
    let message;

    if (age >= 18) {
    message = "You are an adult";
    } else {
    message = "You are a minor";
    }

    console.log(message); // Output: You are an adult

    Same Example Using Ternary Operator

    let age = 18;
    let message = (age >= 18) ? "You are an adult" : "You are a minor";

    console.log(message); // Output: You are an adult

    Much shorter and easier to read.


    When Should You Use It?

    Use the ternary operator when:

    • You have simple true/false conditions
    • You want to assign a value based on a condition
    • You need compact code in return statements or JSX (in React)

    When Not to Use It

    Avoid using it when:

    • You have multiple conditions (use if...else if...else)
    • The logic is too complex and reduces readability

    Real-Life Examples

    Example 1: Login Check

    let isLoggedIn = true;
    let greeting = isLoggedIn ? "Welcome back!" : "Please log in";

    console.log(greeting); // Output: Welcome back!

    Example 2: Check Even or Odd

    let number = 7;
    let result = (number % 2 === 0) ? "Even" : "Odd";

    console.log(result); // Output: Odd

    Example 3: Use in JSX (React)

    <p>{isDarkMode ? "Dark Mode On" : "Light Mode On"}</p>

    Nested Ternary (Use Carefully)

    let score = 85;
    let grade = (score >= 90) ? "A" :
    (score >= 80) ? "B" :
    (score >= 70) ? "C" : "F";

    console.log(grade); // Output: B

    This works, but too many nested ternaries can be hard to read. Use if...else for better clarity in complex logic.


    Bonus Tip: Ternary with Functions

    function getFee(isMember) {
    return isMember ? "$2.00" : "$10.00";
    }

    console.log(getFee(true)); // Output: $2.00
    console.log(getFee(false)); // Output: $10.00

    Summary

    FeatureTernary Operator
    Keyword? :
    PurposeShort if-else
    Return typeExpression value
    Common UseAssignments, JSX
    Readability WarningAvoid nesting too deep

    Final Words

    The ES6 ternary operator is a compact and useful tool to make your JavaScript code more elegant. Use it for simple conditional logic, but always keep readability in mind. With practice, you’ll know exactly when to use it and when to stick to traditional if...else.