programming foundations25 min

Control Flow

How programs make decisions and repeat actions

0/9Not Started

Why This Matters

Without control flow, programs can only run straight through from top to bottom — every line executes exactly once. That's useless for real software. You need programs that can make decisions ("if the user is logged in, show their dashboard") and repeat actions ("process every item in this list").

Control flow is what turns a list of instructions into a program that can think and act conditionally.

Define Terms

Visual Model

Start
score >= 90?
Grade: A
score >= 80?
Grade: B
End
Yes
No
Yes

The full process at a glance. Click Start tour to walk through each step.

A conditional branches the program into different paths based on boolean conditions.

Code Example

Code
// CONDITIONALS: Making decisions
let score = 85;

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

// FOR LOOP: Repeat a known number of times
for (let i = 1; i <= 5; i++) {
  console.log("Count: " + i);
}

// FOR...OF LOOP: Iterate over a collection
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
  console.log("I like " + fruit);
}

// WHILE LOOP: Repeat until a condition changes
let attempts = 0;
while (attempts < 3) {
  console.log("Attempt " + (attempts + 1));
  attempts++;
}

Interactive Experiment

Try these modifications:

  • Change score to different values — verify the correct grade prints.
  • Modify the for loop to count from 10 down to 1.
  • What happens if you set attempts = 3 before the while loop? How many times does it run?
  • Create an infinite loop (carefully!) — what happens?

Quick Quiz

Coding Challenge

FizzBuzz

Write a function called `fizzBuzz` that takes a number `n` and prints numbers from 1 to n. But: for multiples of 3, print 'Fizz'; for multiples of 5, print 'Buzz'; for multiples of both 3 and 5, print 'FizzBuzz'.

Loading editor...

Real-World Usage

Control flow is the backbone of application logic:

  • Authentication: If user credentials are valid → grant access, else → show error.
  • E-commerce: Loop through cart items to calculate total. If total > free shipping threshold → waive shipping.
  • Games: While player is alive → run game loop. If health reaches 0 → game over.
  • Data processing: For each record in dataset → validate, transform, and store.
  • APIs: If request method is GET → return data. If POST → create resource. Else → return 405.

Connections