← Back to Course Overview

Module 4: JavaScript Control Flow

Conditional Statements

Conditional statements let your code make decisions and execute different code blocks based on different conditions.

Understanding the If Statement Structure

If statement diagram

Conditional statements begin with the keyword if. Following the keyword are parentheses where the test or condition lives, and the condition can be any expression. After the parentheses goes a code block. JavaScript evaluates the condition, and only if the resulting value is truthy will the statements inside the code block run.

// the _condition_ or _test_ is inside parens // and the _code block_ is delimited by curly braces let lovingJavaScript = true; if (lovingJavaScript) { console.log('Love JS'); // this line runs only if `lovingJavaScript` is truthy }

Real-World Example

Let's look at how we might use an if statement in a real application for a team running event:

let teamCount = 10; if (teamCount < 12) { //in this case, this statement is true, so the code block will run console.log("Inform the team that they are not a full team."); }

Another example checking if a team member's name is entered:

let name = ""; if (!name) { // name is falsy, so the following code block will execute console.log("Ask the team captain to update the runner's name"); }

Remember: JavaScript evaluates these conditions to either truthy or falsy values. Empty strings, 0, null, undefined, and NaN are all falsy values. Almost everything else is truthy.

Logical Operators

Logical operators allow you to combine multiple conditions in sophisticated ways.

Types of Logical Operators

AND (&&)
OR (||)
NOT (!)

The AND operator (&&) returns true only if both conditions are true:

let isRegistered = true; let hasPaid = true; if (isRegistered && hasPaid) { console.log("Welcome to the event!"); } else { console.log("Please complete registration and payment."); }

In this example, the message "Welcome to the event!" will only display if both isRegistered and hasPaid are true.

The OR operator (||) returns true if at least one condition is true:

let isAdmin = false; let isPremiumUser = true; if (isAdmin || isPremiumUser) { console.log("You have access to premium features."); } else { console.log("Access denied. Upgrade to premium for more features."); }

Here, the message "You have access to premium features." will display if either isAdmin or isPremiumUser is true.

The NOT operator (!) reverses the boolean value:

let isEmailVerified = false; if (!isEmailVerified) { console.log("Please verify your email address."); }

This code checks if email is NOT verified, and if so, displays a prompt to verify.

Combining Logical Operators

let age = 25; let hasTicket = true; let isVIP = false; // Complex condition using multiple logical operators if ((age >= 18 && hasTicket) || isVIP) { console.log("Welcome to the event!"); } else { console.log("Sorry, you cannot enter."); }

This example allows entry if the person is 18 or older AND has a ticket, OR if they are a VIP (regardless of age or ticket status).

Loops

Loops allow you to execute a block of code repeatedly until a specific condition is met.

Types of Loops

For Loop
While Loop
Do-While Loop

The for loop is used when you know in advance how many times you want to execute a block of code:

// Print numbers 1 to 5 for (let i = 1; i <= 5; i++) { console.log("Number " + i); }

A for loop has three parts:

  1. Initialization: let i = 1 - Sets a variable before the loop starts
  2. Condition: i <= 5 - Defines the condition for running the loop
  3. Increment: i++ - Increases a value each time the code block is executed

The while loop executes as long as a specified condition is true:

let count = 1; while (count <= 5) { console.log("Count is: " + count); count++; }

Warning: If you forget to increment the variable used in the condition, the loop will run forever, causing what's known as an "infinite loop."

The do-while loop is a variant of the while loop that executes the code block at least once before checking the condition:

let i = 1; do { console.log("The number is " + i); i++; } while (i <= 5);

This is useful when you want to ensure the code runs at least once, regardless of the condition.

Tip: Choose the appropriate loop based on your needs:

  • Use for when you know the number of iterations.
  • Use while when you don't know how many times the loop will run.
  • Use do-while when you need the code to execute at least once.

Switch Statements

Switch statements offer an alternative to if-else chains when you need to compare a value against multiple options.

Basic Switch Statement

A switch statement evaluates an expression, matching the expression's value against a series of case clauses:

let day = 3; let dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; break; default: dayName = "Invalid day"; } console.log("Today is " + dayName); // Today is Wednesday

Important: Don't forget the break statement after each case! Without it, the code will continue executing the next cases even if the condition is not met.

When to Use Switch vs. If-Else

Use Switch When
Use If-Else When
  • You are comparing a single variable against multiple possible values
  • You have many possible conditions to check
  • The values being compared are fixed values (not ranges)
  • Code readability is a priority for the specific scenario
  • You need to test different expressions (not just one variable)
  • You need to check for ranges of values
  • You have complex conditions using logical operators
  • You have only a few simple conditions to check

Additional Resources

Try It Yourself

Practice using control flow by completing these exercises:

  1. Write a program that determines if a user is eligible for a discount based on their age and membership status.
  2. Create a loop that counts from 10 to 1 and then outputs "Blast off!"
  3. Use a switch statement to display different messages based on a user's role (admin, editor, viewer, etc.).
  4. Create a program that checks if a number is even or odd using conditionals.

Remember to test your code with different inputs to make sure your control flow works correctly!