The Conditional (Ternary) Operator

Jul 4, 2024

Lecture Notes: The Conditional (Ternary) Operator

Overview

  • The conditional operator is another way of writing conditionals, along with if-else statements and switch statements.
  • Also known as the ternary operator because it has three parts.

Syntax

  • Ternary operator allows writing an if-else statement in one line.
  • Basic form:
    condition ? exprIfTrue : exprIfFalse
    
  • condition: The condition to evaluate (e.g., age >= 18).
  • exprIfTrue: Expression to execute if condition is true (e.g., console.log('I like to drink wine')).
  • exprIfFalse: Expression to execute if condition is false (e.g., console.log('I like to drink water')).

Example

  1. Defining a variable age:
    const age = 23;
    
  2. Using the ternary operator for a simple if-else logic:
    age >= 18 ? console.log('I like to drink wine') : console.log('I like to drink water');
    
  3. Result:
    • Outputs: I like to drink wine if age is 23 because the condition is true.
    • Outputs: I like to drink water if age is 15 because the condition is false.

Advantages

  • Ternary operator is an operator, which means it produces a value.
  • This allows for conditional variable declarations in a concise way:
    const drink = age >= 18 ? 'wine' : 'water';
    console.log(drink);
    // Outputs: 'wine'
    
  • More concise and readable compared to traditional if-else blocks:
    let drink;
    if (age >= 18) {
      drink = 'wine';
    } else {
      drink = 'water';
    }
    console.log(drink);
    // Outputs: 'wine'
    

Application in Template Literals

  • Ternary operator can be used inside template literals:
    console.log(`I like to drink ${age >= 18 ? 'wine' : 'water'}`);
    // Outputs: 'I like to drink wine'
    
  • Conducive for quick decisions and places expecting an expression.

Important Notes

  • Ternary operator is not a replacement for if-else statements.
  • Ideal for one-liners and simple conditional logic.
  • if-else is still needed for executing larger blocks of code based on conditions.

Conclusion

  • Ternary operator simplifies code by reducing multi-line if-else statements to single-line expressions.
  • Particularly useful within template literals and when variables need to be conditionally declared.

Recommendation

  • Make sure to fully understand how the ternary operator works.
  • Practice by using it in various coding scenarios to gain familiarity.