Control Flow

Control flow is how you make your programs smart. Instead of just running code line by line, you can make decisions (if/else) and repeat actions (loops). This is where your code becomes truly powerful!

What You'll Learn

  • How to use if/else statements to make decisions
  • Different types of loops for repeating code
  • The ternary operator for simple conditions
  • When to use break and continue

If Statements

If statements let your code make decisions:

let temperature = 75;

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

if (temperature <= 80) {
  console.log("The weather is nice!");
}

If/Else Statements

Use else to handle the alternative case:

let age = 20;

if (age >= 18) {
  console.log("You are an adult");
} else {
  console.log("You are a minor");
}

// Another example
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 if (score >= 60) {
  console.log("Grade: D");
} else {
  console.log("Grade: F");
}

Comparison Operators

These operators are used in conditions:

let x = 10;
let y = 20;

console.log("x === y:", x === y);  // Equal to (strict)
console.log("x !== y:", x !== y);  // Not equal to
console.log("x < y:", x < y);      // Less than
console.log("x > y:", x > y);      // Greater than
console.log("x <= y:", x <= y);    // Less than or equal
console.log("x >= y:", x >= y);    // Greater than or equal

Logical Operators

Combine multiple conditions:

let age = 25;
let hasLicense = true;

// AND operator (&&) - both must be true
if (age >= 18 && hasLicense) {
  console.log("You can drive!");
}

// OR operator (||) - at least one must be true
let isWeekend = true;
let isHoliday = false;

if (isWeekend || isHoliday) {
  console.log("You can relax!");
}

// NOT operator (!) - reverses the condition
let isSleeping = false;

if (!isSleeping) {
  console.log("You are awake!");
}

Ternary Operator

A shorthand for simple if/else statements:

// Syntax: condition ? valueIfTrue : valueIfFalse

let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log("Status:", status);

// Another example
let score = 85;
let result = score >= 60 ? "Pass" : "Fail";
console.log("Result:", result);

// You can use it directly
console.log("Can vote:", age >= 18 ? "Yes" : "No");

For Loops

Repeat code a specific number of times:

// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
  console.log("Count:", i);
}

// Countdown from 5 to 1
for (let i = 5; i >= 1; i--) {
  console.log("Countdown:", i);
}

// Count by 2s
for (let i = 0; i <= 10; i += 2) {
  console.log("Even number:", i);
}

While Loops

Repeat code while a condition is true:

// Count to 5 with while loop
let count = 1;
while (count <= 5) {
  console.log("While count:", count);
  count++;
}

// Find first power of 2 greater than 100
let power = 1;
while (power <= 100) {
  power = power * 2;
}
console.log("First power of 2 > 100:", power);

Do-While Loops

Like while loops, but always run at least once:

let num = 1;

do {
  console.log("Number:", num);
  num++;
} while (num <= 3);

// This runs once even though condition is false
let x = 10;
do {
  console.log("This prints once, x =", x);
} while (x < 5);

Break and Continue

Control loop execution:

// Break - exit the loop early
console.log("Using break:");
for (let i = 1; i <= 10; i++) {
  if (i === 5) {
    console.log("Breaking at", i);
    break;
  }
  console.log(i);
}

// Continue - skip to next iteration
console.log("\nUsing continue:");
for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    console.log("Skipping", i);
    continue;
  }
  console.log(i);
}

Practical Examples

Let's combine what we've learned:

// Find all even numbers from 1 to 10
console.log("Even numbers from 1 to 10:");
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    console.log(i);
  }
}

// FizzBuzz (classic programming challenge)
console.log("\nFizzBuzz:");
for (let i = 1; i <= 15; i++) {
  if (i % 3 === 0 && i % 5 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

// Calculate factorial
let n = 5;
let factorial = 1;
for (let i = 1; i <= n; i++) {
  factorial *= i;
}
console.log("\nFactorial of", n, "is", factorial);

Try It Yourself

Practice control flow with these exercises:

// 1. Check if a number is positive, negative, or zero
let number = 10;
if (number > 0) {
  console.log("Positive");
} else if (number < 0) {
  console.log("Negative");
} else {
  console.log("Zero");
}

// 2. Print numbers from 1 to 10
for (let i = 1; i <= 10; i++) {
  console.log(i);
}

// 3. Find the sum of numbers from 1 to 100
let sum = 0;
for (let i = 1; i <= 100; i++) {
  sum += i;
}
console.log("Sum from 1 to 100:", sum);

// 4. Create a password checker
let password = "secret123";
let correctPassword = "javascript";

if (password === correctPassword) {
  console.log("Access granted!");
} else {
  console.log("Access denied!");
}

// Try creating your own conditions and loops!

Key Takeaways

  • Use if/else statements to make decisions in your code
  • Comparison operators (===, !==, <, >, <=, >=) compare values
  • Logical operators (&&, ||, !) combine conditions
  • for loops are best when you know how many times to repeat
  • while loops are best when you repeat until a condition changes
  • break exits a loop, continue skips to the next iteration

Next Steps

Congratulations! You've learned the fundamentals of control flow. Next, we'll explore data structures - how to work with collections of data like arrays and objects!

Pro Tip: When writing loops, always make sure your condition will eventually become false. Otherwise, you'll create an infinite loop that never stops! Also, practice reading other people's code to see different ways of solving problems with control flow.

Control Flow | LearningJavaScript.org