J

JavaScript Handbook

Clean • Professional

Ternary Operator (? :)

1 minute

Conditional (Ternary) Operator (? :)

The ternary operator is a shortcut for if...else. It has three parts: condition ? value_if_true : value_if_false.

condition ? expression_if_true : expression_if_false;
  • condition → A boolean expression that evaluates to true or false.
  • expression_if_true → The value or code executed if the condition is true.
  • expression_if_false → The value or code executed if the condition is false.

1. Basic Example

  • Checks if age >= 18.
  • If true → assigns 'Adult' to status.
  • If false → assigns 'Minor'.
  • Much shorter than writing a full if...else.
let age = 18;
let status = (age >= 18) ? 'Adult' : 'Minor';
console.log(status); // "Adult"

2. Using Numbers

  • Checks if the number is even (num % 2 === 0).
  • If true → 'Even'.
  • If false → 'Odd'.
let num = 10;
let result = (num % 2 === 0) ? 'Even' : 'Odd';
console.log(result); // "Even"

3. Nested Ternary Operators

You can nest ternary operators, but readability decreases if overused:

let marks = 85;
let grade = (marks >= 90) ? 'A+' :
            (marks >= 75) ? 'A' :
            (marks >= 60) ? 'B' : 'C';
console.log(grade); // "A"

4. Using Ternary in Functions

  • Ternary can be used directly in functions to return values.
  • Makes code shorter and cleaner than a full if...else.
function checkAge(age) {
  return (age >= 18) ? 'Eligible to vote' : 'Not eligible to vote';
}

console.log(checkAge(20)); // "Eligible to vote"

 

Article 0 of 0