From Zero to AI

Lesson 1.4: Conditions

Duration: 50 minutes

Learning Objectives

By the end of this lesson, you will be able to:

  • Use if statements to execute code conditionally
  • Chain conditions with else if and else
  • Use switch statements for multiple options
  • Combine conditions with logical operators
  • Write clean, readable conditional code

Why Conditions?

Programs need to make decisions. Should the user see a login button or a logout button? Is the password correct? Is the shopping cart empty?

Conditions let your code choose different paths based on circumstances:

const isLoggedIn = true;

if (isLoggedIn) {
  console.log('Welcome back!');
} else {
  console.log('Please log in');
}

The if Statement

The most basic conditional: run code only if a condition is true.

const temperature = 30;

if (temperature > 25) {
  console.log("It's hot outside!");
}

Syntax

if (condition) {
  // Code runs if condition is true
}

Multiple Statements

const score = 95;

if (score >= 90) {
  console.log('Excellent!');
  console.log('You got an A!');
  console.log('Keep up the great work!');
}

The else Clause

Run alternative code when the condition is false.

const age = 15;

if (age >= 18) {
  console.log('You can vote');
} else {
  console.log('You cannot vote yet');
}

Practical Example: Login Status

const isAuthenticated = false;

if (isAuthenticated) {
  console.log('Dashboard');
  console.log('Settings');
  console.log('Logout');
} else {
  console.log('Login');
  console.log('Register');
}

The else if Chain

Check multiple conditions in sequence.

const score = 75;

if (score >= 90) {
  console.log('Grade: A');
} else if (score >= 80) {
  console.log('Grade: B');
} else if (score >= 70) {
  console.log('Grade: C');
} else if (score >= 60) {
  console.log('Grade: D');
} else {
  console.log('Grade: F');
}

Important: Conditions are checked from top to bottom. The first true condition wins.

const value = 100;

// Only "Greater than 50" prints, even though 100 is also > 75
if (value > 50) {
  console.log('Greater than 50');
} else if (value > 75) {
  console.log('Greater than 75'); // Never reached
}

Order Matters

Put more specific conditions first:

const score = 95;

// Wrong order - always matches first condition
if (score >= 60) {
  console.log('Pass'); // This runs for score 95
} else if (score >= 90) {
  console.log('Excellent'); // Never reached
}

// Correct order - most specific first
if (score >= 90) {
  console.log('Excellent'); // This runs for score 95
} else if (score >= 60) {
  console.log('Pass');
}

Combining Conditions

Use logical operators to check multiple things at once.

AND (&&) - All Must Be True

const age = 25;
const hasLicense = true;
const hasCar = true;

if (age >= 18 && hasLicense && hasCar) {
  console.log('You can drive!');
}

OR (||) - At Least One Must Be True

const isWeekend = false;
const isHoliday = true;

if (isWeekend || isHoliday) {
  console.log('Day off!');
}

Complex Conditions

Use parentheses for clarity:

const age = 25;
const isStudent = false;
const isSenior = false;

// Discount for students, seniors, OR young people (under 18)
if (isStudent || isSenior || age < 18) {
  console.log('You get a discount!');
}

// Must be adult AND (have ID OR have passport)
const hasID = true;
const hasPassport = false;

if (age >= 18 && (hasID || hasPassport)) {
  console.log('Identity verified');
}

Nested Conditions

Conditions inside conditions:

const isLoggedIn = true;
const isAdmin = true;

if (isLoggedIn) {
  console.log('Welcome!');

  if (isAdmin) {
    console.log('Admin panel available');
  } else {
    console.log('User dashboard');
  }
} else {
  console.log('Please log in');
}

Tip: Avoid deep nesting. Consider restructuring:

// Instead of deep nesting
if (isLoggedIn) {
  if (isAdmin) {
    if (hasPermission) {
      // Do something
    }
  }
}

// Use early returns or combined conditions
if (!isLoggedIn) {
  console.log('Please log in');
  return;
}

if (isAdmin && hasPermission) {
  // Do something
}

The switch Statement

Best for checking one value against many options.

const day = 'Monday';

switch (day) {
  case 'Monday':
    console.log('Start of the week');
    break;
  case 'Tuesday':
  case 'Wednesday':
  case 'Thursday':
    console.log('Midweek');
    break;
  case 'Friday':
    console.log('Almost weekend!');
    break;
  case 'Saturday':
  case 'Sunday':
    console.log('Weekend!');
    break;
  default:
    console.log('Invalid day');
}

Key Points

  1. break: Stops execution and exits the switch
  2. default: Runs if no case matches (like else)
  3. Fall-through: Without break, execution continues to next case

Forgetting break

const fruit = 'apple';

// Bug: missing break causes fall-through
switch (fruit) {
  case 'apple':
    console.log("It's an apple");
  // Missing break!
  case 'banana':
    console.log("It's a banana"); // This also runs!
    break;
}
// Output:
// "It's an apple"
// "It's a banana"

Intentional Fall-through

Sometimes useful for grouping cases:

const month = 3;
let season;

switch (month) {
  case 12:
  case 1:
  case 2:
    season = 'Winter';
    break;
  case 3:
  case 4:
  case 5:
    season = 'Spring';
    break;
  case 6:
  case 7:
  case 8:
    season = 'Summer';
    break;
  case 9:
  case 10:
  case 11:
    season = 'Fall';
    break;
  default:
    season = 'Unknown';
}

console.log(season); // "Spring"

When to Use if vs switch

Use if When:

  • Checking ranges (score >= 90)
  • Complex conditions with && or ||
  • Different variables in each condition
// if is better here
if (score >= 90) {
  grade = 'A';
} else if (score >= 80) {
  grade = 'B';
}

Use switch When:

  • Checking one variable against specific values
  • Many exact-match cases
  • Grouping cases that share behavior
// switch is better here
switch (status) {
  case 'pending':
    handlePending();
    break;
  case 'approved':
    handleApproved();
    break;
  case 'rejected':
    handleRejected();
    break;
}

Truthy and Falsy in Conditions

Remember: conditions evaluate to boolean.

const username = '';

// Empty string is falsy
if (username) {
  console.log(`Hello, ${username}`);
} else {
  console.log('Hello, Guest'); // This runs
}

// Common falsy values in conditions
if (!0) console.log('0 is falsy');
if (!'') console.log('Empty string is falsy');
if (!null) console.log('null is falsy');
if (!undefined) console.log('undefined is falsy');

Checking for Values

// Check if array has items
const items = [1, 2, 3];
if (items.length) {
  console.log('Array has items');
}

// Check if string has content
const name = 'Alice';
if (name) {
  console.log(`Name is: ${name}`);
}

// Check if object property exists
const user = { name: 'Alice' };
if (user.name) {
  console.log(`User name: ${user.name}`);
}

Practical Examples

Example 1: User Authentication

const username = 'admin';
const password = 'secret123';
const isActive = true;

if (!username || !password) {
  console.log('Please enter username and password');
} else if (username === 'admin' && password === 'secret123') {
  if (isActive) {
    console.log('Login successful!');
  } else {
    console.log('Account is deactivated');
  }
} else {
  console.log('Invalid credentials');
}

Example 2: Shopping Cart

const cartItems = 3;
const cartTotal = 75;
const isMember = true;

let shipping;

if (cartItems === 0) {
  console.log('Your cart is empty');
} else {
  // Free shipping for members or orders over $50
  if (isMember || cartTotal >= 50) {
    shipping = 0;
    console.log('Free shipping!');
  } else {
    shipping = 5.99;
    console.log(`Shipping: $${shipping}`);
  }

  console.log(`Total: $${cartTotal + shipping}`);
}

Example 3: HTTP Status Handler

const statusCode = 404;

switch (statusCode) {
  case 200:
    console.log('Success');
    break;
  case 201:
    console.log('Created');
    break;
  case 400:
    console.log('Bad Request');
    break;
  case 401:
    console.log('Unauthorized');
    break;
  case 403:
    console.log('Forbidden');
    break;
  case 404:
    console.log('Not Found');
    break;
  case 500:
    console.log('Server Error');
    break;
  default:
    console.log(`Unknown status: ${statusCode}`);
}

Example 4: Time-Based Greeting

const hour = new Date().getHours();
let greeting;

if (hour < 6) {
  greeting = 'Good night';
} else if (hour < 12) {
  greeting = 'Good morning';
} else if (hour < 18) {
  greeting = 'Good afternoon';
} else if (hour < 22) {
  greeting = 'Good evening';
} else {
  greeting = 'Good night';
}

console.log(`${greeting}!`);

Exercises

Exercise 1: Age Category

Write code that prints the category based on age:

  • 0-12: "Child"
  • 13-19: "Teenager"
  • 20-64: "Adult"
  • 65+: "Senior"
const age = 25;
Solution
const age = 25;
let category;

if (age < 0) {
  category = 'Invalid age';
} else if (age <= 12) {
  category = 'Child';
} else if (age <= 19) {
  category = 'Teenager';
} else if (age <= 64) {
  category = 'Adult';
} else {
  category = 'Senior';
}

console.log(`Category: ${category}`); // "Adult"

Exercise 2: Ticket Price

Calculate ticket price based on:

  • Regular price: $12
  • Children (under 12): 50% off
  • Seniors (65+): 30% off
  • Students: 20% off (check isStudent boolean)
const age = 20;
const isStudent = true;
Solution
const age = 20;
const isStudent = true;
const regularPrice = 12;
let price;

if (age < 12) {
  price = regularPrice * 0.5;
  console.log('Child discount applied');
} else if (age >= 65) {
  price = regularPrice * 0.7;
  console.log('Senior discount applied');
} else if (isStudent) {
  price = regularPrice * 0.8;
  console.log('Student discount applied');
} else {
  price = regularPrice;
  console.log('Regular price');
}

console.log(`Ticket price: $${price.toFixed(2)}`);

Exercise 3: Day Type

Use a switch statement to print:

  • "Weekday" for Monday-Friday
  • "Weekend" for Saturday-Sunday
  • "Invalid" for anything else
const day = 'Wednesday';
Solution
const day = 'Wednesday';
let dayType;

switch (day) {
  case 'Monday':
  case 'Tuesday':
  case 'Wednesday':
  case 'Thursday':
  case 'Friday':
    dayType = 'Weekday';
    break;
  case 'Saturday':
  case 'Sunday':
    dayType = 'Weekend';
    break;
  default:
    dayType = 'Invalid';
}

console.log(`${day} is a ${dayType}`);

Key Takeaways

  1. if runs code when a condition is true
  2. else provides an alternative when the condition is false
  3. else if chains multiple conditions - first match wins
  4. Order matters - put specific conditions before general ones
  5. switch is cleaner for multiple exact-value checks
  6. Always include break in switch cases (unless intentional fall-through)
  7. Use parentheses to make complex conditions clear

Resources

Resource Type Description
MDN: if...else Documentation Official if/else reference
MDN: switch Documentation Official switch reference
JavaScript.info: Conditional Branching Tutorial Interactive conditions tutorial

Next Lesson

Now that you can make decisions, let's learn how to repeat actions with loops.

Continue to Lesson 1.5: Loops