JAVASCRIPT Tutorial

Ternary Operator

What is a Ternary Operator?

The ternary operator (?:) is a shorthand way to express conditional expressions, providing a concise alternative to if-else statements.

How to Use the Ternary Operator:

Follow these steps:

  1. Condition: Write the condition that determines the output.
  2. Question Mark (?): Place a question mark (?) after the condition.
  3. True Expression: Write the expression that will be executed if the condition is true.
  4. Colon (:): Place a colon (:) after the true expression.
  5. False Expression: Write the expression that will be executed if the condition is false.
Syntax:
condition ? true_expression : false_expression

Example in JavaScript:

let isRaining = true;
let message = isRaining ? "Stay indoors" : "Go for a walk";
console.log(message); // Output: "Stay indoors"

Key Concepts:

  • Conditional Expression: The ternary operator allows for concise conditional expressions.
  • Shorthand: It's a shorthand notation for if-else statements.
  • Conditional Logic: The ternary operator evaluates conditions and returns different values based on their truthiness.

Benefits:

  • Improves code readability
  • Simplifies conditional statements
  • Reduces the number of lines of code