Control Flow: Making Decisions and Repeating Actions

8 min read

Control Flow: Making Decisions and Repeating Actions ⚙️

Welcome, intrepid coder! So far, our JavaScript code has been like a straight road - it executes from top to bottom, one line after another. But what if we want our code to make decisions? What if we want it to take different paths based on certain conditions, or repeat actions without us having to write the same code over and over? That's where Control Flow comes in. It's the traffic cop of your code, directing the flow of execution.

Think of it like your morning routine. You don't just do the same exact things in the same order every single day, do you? If it's raining, you grab an umbrella. If you're out of coffee, you make a tea instead. If you have a bunch of emails to send, you sit down and power through them one by one. Your brain is constantly making decisions and repeating actions. In this guide, we'll teach your JavaScript code to do the same!


1. Conditional Logic: If, Else, and Else If Statements 🤔

The Problem: Our code needs to make a choice. It needs to execute a certain block of code only if a specific condition is true.

Imagine you're building a simple age verification for a website. If the user is 18 or older, you want to grant them access. If not, you want to show them a different message. How do you do that?

The Solution: The if statement! It's the most fundamental decision-making tool in JavaScript.

An if statement tells your program to execute a block of code only if a certain condition is true.

javascript
let age = 25;

if (age >= 18) {
  console.log("Welcome! You have access.");
}

In this example, the condition is age >= 18. Since age is 25, this condition is true, and the message is logged to the console. If age was 16, nothing would happen.

But what if we want to do something specific when the condition is false? That's where else comes to the rescue.

The else statement provides an alternative block of code to execute when the if condition is false.

javascript
let age = 16;

if (age >= 18) {
  console.log("Welcome! You have access.");
} else {
  console.log("Sorry, you must be 18 or older to enter.");
}

Now, our code handles both possibilities. It's like a fork in the road.

What if you have more than two possibilities? Let's say you want to show a special message for users who are exactly 18. You can use an else if statement to chain multiple conditions.

javascript
let age = 18;

if (age > 18) {
  console.log("Welcome! You have access.");
} else if (age === 18) {
  console.log("Congratulations on turning 18! Welcome!");
} else {
  console.log("Sorry, you must be 18 or older to enter.");
}

You can have as many else if statements as you need. Just remember, only the first true condition's code block will execute.

🧠 Under the Hood: When the JavaScript engine encounters an if statement, it evaluates the condition inside the parentheses. If the result is "truthy" (anything that's not false, 0, "", null, undefined, or NaN), the code block is executed. Otherwise, it skips to the next else if or else.


2. Comparison and Logical Operators: &&, ||, and Strict Equality (===) 🧐

The Problem: The conditions in our if statements are often simple. But what if we need to check multiple things at once? For instance, to get a driver's license, you need to be at least 16 and have passed the driving test.

The Solution: Logical operators! They allow us to combine multiple conditions.

  • && (AND): This operator checks if both conditions are true. Think of it as a very strict bouncer at a club. You need to have your ID and be on the list.

    javascript
    let age = 17;
    let hasDrivingLicense = true;
    
    if (age >= 16 && hasDrivingLicense) {
      console.log("You are eligible to drive.");
    } else {
      console.log("You are not eligible to drive.");
    }
  • || (OR): This operator checks if at least one of the conditions is true. Imagine a vending machine that accepts cash or a credit card.

    javascript
    let hasCash = false;
    let hasCreditCard = true;
    
    if (hasCash || hasCreditCard) {
      console.log("You can buy a snack!");
    } else {
      console.log("Sorry, you need a way to pay.");
    }

Strict Equality (===)

You might have seen == (loose equality) in older code. While it might seem easier, it can lead to some truly bizarre and frustrating bugs because it performs type coercion. This means it tries to convert the values to a common type before comparing them.

For example, 5 == "5" is true. This is rarely what you want.

The industry standard and best practice is to always use === (strict equality). It checks if the values are equal and if they are of the same data type, without any type conversion.

5 === "5" is false. Much better!

A Funny Exaggeration: Using == is like asking your friend if they have "five" and they hand you a picture of the number 5. You technically got what you asked for, but it's not what you meant. === ensures you get the actual five-dollar bill you were expecting.


3. The Switch Statement: Handling Multiple Distinct Conditions 🚦

The Problem: We have a single value that could be one of several distinct options, and we need to perform a different action for each. Using a long chain of if...else if...else statements can get clunky and hard to read.

Imagine you're building a program that gives you a different greeting based on the day of the week.

The Solution: The switch statement! It provides a cleaner way to handle multiple distinct conditions for a single value.

javascript
let day = "Tuesday";
let greeting = "";

switch (day) {
  case "Monday":
    greeting = "Ugh, it's Monday.";
    break;
  case "Tuesday":
    greeting = "Taco Tuesday!";
    break;
  case "Wednesday":
    greeting = "Hump day!";
    break;
  case "Thursday":
    greeting = "Almost there...";
    break;
  case "Friday":
    greeting = "TGIF!";
    break;
  default:
    greeting = "Enjoy the weekend!";
}

console.log(greeting); // Output: Taco Tuesday!

How it works:

  • The switch statement evaluates the expression in the parentheses (day in this case).
  • It then compares the result to the value of each case.
  • If a match is found, the code block for that case is executed.
  • The break keyword is crucial! It tells JavaScript to exit the switch statement. Without it, the code will "fall through" and execute the code in the next case as well, which is usually not what you want.
  • The default case is optional, but highly recommended. It acts as a catch-all if none of the case values match.

When to use switch vs. if...else if:

  • Use switch when you are comparing a single value against multiple distinct options.
  • Use if...else if for more complex conditions, like checking ranges (age > 18) or using logical operators (&&, ||).

4. Loops: Automating Repetition with For and While Loops 🔁

The Problem: We need to perform the same action multiple times. Writing the same line of code over and over is tedious and inefficient.

Imagine you need to print the numbers from 1 to 100. You wouldn't want to write console.log(1), console.log(2), and so on, 100 times. That's a recipe for carpal tunnel and madness.

The Solution: Loops! They allow us to execute a block of code repeatedly as long as a certain condition is true.

The for loop

The for loop is ideal when you know in advance how many times you want the loop to run.

Its syntax has three parts, separated by semicolons:

  1. Initialization: A statement that is executed before the loop starts (e.g., let i = 0).
  2. Condition: An expression that is evaluated before each iteration. If it's true, the loop continues.
  3. Increment/Decrement: A statement that is executed at the end of each iteration (e.g., i++).
javascript
for (let i = 1; i <= 5; i++) {
  console.log("This is loop number " + i);
}

Output:

ada
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4
This is loop number 5

Let's break that down:

  1. let i = 1;: We start with a counter variable i set to 1.
  2. i <= 5;: The loop will continue as long as i is less than or equal to 5.
  3. console.log(...): This is the code that gets executed in each iteration.
  4. i++: After each iteration, i is incremented by 1.

The while loop

The while loop is perfect when you don't know exactly how many times the loop will run, but you know the condition that should stop it.

It's simpler than a for loop. It just keeps running as long as its condition is true.

javascript
let count = 0;

while (count < 3) {
  console.log("The count is " + count);
  count++;
}

Output:

applescript
The count is 0
The count is 1
The count is 2

An Interesting Fact: A common pitfall with while loops is creating an infinite loop. This happens if the condition never becomes false. For example, if we forgot the count++ line in the example above, count would always be 0, and the loop would run forever (or until the browser crashes!). It's like a vinyl record that's stuck on a scratch.

Real-world scenario: Imagine a game where a character keeps attacking an enemy until the enemy's health is 0. A while loop is perfect for this: while (enemyHealth > 0) { // keep attacking }.

Further Reading & Resources 📚

Challenge

Challenge: User Activity Log Processor

You are tasked with creating a function to process a log of user activities for an e-commerce website. Your function needs to iterate through a list of activities, categorize them, count specific high-priority events, and stop processing once a certain threshold is met.

Requirements:

  1. Create a function named processUserActivity that accepts one argument: activities, which is an array of activity objects.
  2. Initialize three counters: totalProcessed (for all activities looked at), highPriorityCount (for specific important activities), and unclassifiedCount (for activities with an unknown type).
  3. Iterate through the activities array using a loop. The loop must terminate immediately as soon as highPriorityCount reaches 3.
  4. Inside the loop, use a switch statement to handle the activity type.
    • Handle the cases: 'purchase', 'review', and 'login'.
    • Any other activity type should be considered unclassified. Increment unclassifiedCount and proceed to the next iteration.
  5. For the 'purchase' case, use conditional logic to check if it's a high-priority event. A purchase is high-priority if the userStatus is 'premium' AND the value is greater than 100.
    • If it is a high-priority event, increment highPriorityCount.
  6. Before the loop ends each iteration (and before checking the termination condition), increment the totalProcessed counter.
  7. The function must return an object with the final counts: { totalProcessed, highPriorityCount, unclassifiedCount }.

Expected result

Your function should return a JavaScript object containing the final state of the three counters after processing the userActivities array according to the rules.

Given the sample data, the loop should process the first 8 items and stop after finding the 3rd high-priority event. The expected return object is:

json
{
  "totalProcessed": 8,
  "highPriorityCount": 3,
  "unclassifiedCount": 1
}
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.