Lesson 7: JavaScript Conditional Operators

Master JavaScript conditional operators with interactive examples and real-world applications.

7.1 Conditional (Ternary) Operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands. It provides a shorthand way to write simple conditional statements.

Syntax: condition ? exprIfTrue : exprIfFalse

Condition

An expression that evaluates to true or false

Expression 1

Executed if condition is true

Expression 2

Executed if condition is false

Basic Example

let age = 18;
let status = (age >= 18) ? 'Adult' : 'Minor';
console.log(status); // Output: Adult

Example 7.1: Find Larger Number

let x = 10;
let y = 20;
let larger = (x > y) ? x : y;
document.write(larger); // Output: 20

7.2 Interactive Ternary Demos

Try these interactive demos to see the ternary operator in action:

Number Comparison

Results will appear here

Even/Odd Check

Result will appear here

Login Check

Result will appear here

Discount Calculator

Result will appear here

7.3 Advanced Ternary Usage

Ternary operators can be nested for more complex conditions, though this should be done carefully for readability.

Nested Ternary Example

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

Example 7.2: Grade Calculator

function getGrade(score) {
  return (score >= 90) ? 'A' :
         (score >= 80) ? 'B' :
         (score >= 70) ? 'C' :
         (score >= 60) ? 'D' : 'F';
}

let studentScore = 85;
document.write(`Score: ${studentScore}, Grade: ${getGrade(studentScore)}`);

Try the Grade Calculator

Grade will appear here

7.4 Practical Applications

Conditional operators are widely used in real-world JavaScript applications for concise conditional logic.

Example 7.3: Conditional Styling

function updateTheme(isDarkMode) {
  const theme = isDarkMode ? 'dark' : 'light';
  document.body.className = theme;
  document.getElementById('themeStatus').textContent = 
    `Current theme: ${theme}`;
}

// Toggle between dark and light mode
let darkMode = false;
document.getElementById('toggleTheme').addEventListener('click', () => {
  darkMode = !darkMode;
  updateTheme(darkMode);
});

Theme Switcher Demo

Current theme: light

Example 7.4: Form Validation

function validateForm() {
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  
  const isValid = 
    username.length >= 6 && 
    password.length >= 8;
  
  const message = isValid 
    ? 'Form is valid. Submitting...' 
    : 'Form is invalid. Please check your inputs.';
  
  document.getElementById('validationResult').textContent = message;
  
  return isValid;
}