From Zero to AI

Lesson 1.5: Loops

Duration: 50 minutes

Learning Objectives

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

  • Use for loops to repeat code a specific number of times
  • Use while loops when the number of iterations is unknown
  • Iterate over arrays with for...of
  • Control loop execution with break and continue
  • Choose the right loop for different situations

Why Loops?

Imagine you need to print numbers 1 to 100. Without loops, you would write 100 console.log statements. With loops, it takes 3 lines:

for (let i = 1; i <= 100; i++) {
  console.log(i);
}

Loops repeat code until a condition is met.


The for Loop

The most common loop. Use when you know how many times to repeat.

Syntax

for (initialization; condition; update) {
  // Code to repeat
}
  • Initialization: Runs once before the loop starts
  • Condition: Checked before each iteration; loop continues while true
  • Update: Runs after each iteration

Basic Example

for (let i = 0; i < 5; i++) {
  console.log(i);
}
// Output: 0, 1, 2, 3, 4

Step by step:

  1. let i = 0 - Initialize counter
  2. i < 5 - Check condition (0 < 5 = true)
  3. Print 0
  4. i++ - Increment counter (i = 1)
  5. i < 5 - Check condition (1 < 5 = true)
  6. Print 1
  7. ... continues until i = 5
  8. i < 5 - Check condition (5 < 5 = false)
  9. Loop ends

Common Patterns

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

// Count down from 10 to 1
for (let i = 10; i >= 1; i--) {
  console.log(i);
}

// Skip by 2 (even numbers)
for (let i = 0; i <= 10; i += 2) {
  console.log(i); // 0, 2, 4, 6, 8, 10
}

// Skip by 2 (odd numbers)
for (let i = 1; i <= 10; i += 2) {
  console.log(i); // 1, 3, 5, 7, 9
}

Looping Through Arrays

Arrays are ordered collections of items. Loops are perfect for processing each item.

const fruits = ['apple', 'banana', 'cherry'];

// Using index-based for loop
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output: apple, banana, cherry

Array Index

Arrays are zero-indexed (first item is at position 0):

const colors = ['red', 'green', 'blue'];
//              [0]      [1]      [2]

console.log(colors[0]); // "red"
console.log(colors[1]); // "green"
console.log(colors[2]); // "blue"
console.log(colors.length); // 3

The for...of Loop

A cleaner way to iterate over arrays when you don't need the index.

const fruits = ['apple', 'banana', 'cherry'];

for (const fruit of fruits) {
  console.log(fruit);
}
// Output: apple, banana, cherry

When to Use Each

const items = ['a', 'b', 'c'];

// Use for...of when you only need the value
for (const item of items) {
  console.log(item);
}

// Use traditional for when you need the index
for (let i = 0; i < items.length; i++) {
  console.log(`Item ${i}: ${items[i]}`);
}

Iterating Over Strings

Strings can also be iterated character by character:

const word = 'Hello';

for (const char of word) {
  console.log(char);
}
// Output: H, e, l, l, o

The while Loop

Use when you don't know how many iterations you need.

Syntax

while (condition) {
  // Code to repeat
}

Basic Example

let count = 0;

while (count < 5) {
  console.log(count);
  count++;
}
// Output: 0, 1, 2, 3, 4

Practical Example: User Input Simulation

let attempts = 0;
const maxAttempts = 3;
let success = false;

while (attempts < maxAttempts && !success) {
  attempts++;
  console.log(`Attempt ${attempts}...`);

  // Simulate random success
  if (Math.random() > 0.5) {
    success = true;
    console.log('Success!');
  }
}

if (!success) {
  console.log('Max attempts reached');
}

Danger: Infinite Loops

If the condition never becomes false, the loop runs forever:

// DO NOT RUN - This will freeze your program
let x = 1;
while (x > 0) {
  // x will always be > 0
  console.log(x);
  x++; // x keeps increasing
}

Always ensure your loop condition will eventually become false.


The do...while Loop

Like while, but guarantees at least one execution.

let i = 0;

do {
  console.log(i);
  i++;
} while (i < 5);
// Output: 0, 1, 2, 3, 4

Difference from while

// while - might not run at all
let x = 10;
while (x < 5) {
  console.log('This never runs');
}

// do...while - always runs at least once
let y = 10;
do {
  console.log('This runs once'); // This prints!
} while (y < 5);

Controlling Loop Flow

break - Exit the Loop

Stop the loop immediately:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break; // Exit loop when i equals 5
  }
  console.log(i);
}
// Output: 0, 1, 2, 3, 4

continue - Skip to Next Iteration

Skip the rest of the current iteration:

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue; // Skip when i equals 2
  }
  console.log(i);
}
// Output: 0, 1, 3, 4 (2 is skipped)

Practical Examples

// Find first even number
const numbers = [1, 3, 4, 7, 8];

for (const num of numbers) {
  if (num % 2 === 0) {
    console.log(`First even: ${num}`);
    break; // Stop after finding first
  }
}

// Skip negative numbers
const values = [1, -2, 3, -4, 5];

for (const value of values) {
  if (value < 0) {
    continue; // Skip negative
  }
  console.log(value); // Only positive printed
}
// Output: 1, 3, 5

Nested Loops

Loops inside loops:

// Multiplication table
for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    console.log(`${i} x ${j} = ${i * j}`);
  }
}
// Output:
// 1 x 1 = 1
// 1 x 2 = 2
// 1 x 3 = 3
// 2 x 1 = 2
// ... and so on

Working with 2D Data

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

for (let row = 0; row < matrix.length; row++) {
  for (let col = 0; col < matrix[row].length; col++) {
    console.log(`Row ${row}, Col ${col}: ${matrix[row][col]}`);
  }
}

Choosing the Right Loop

Situation Best Loop
Known number of iterations for
Need the index for
Iterating over array values for...of
Unknown iterations, check before while
Unknown iterations, run at least once do...while
Iterating over object keys for...in

Practical Examples

Example 1: Sum of Numbers

const numbers = [10, 20, 30, 40, 50];
let sum = 0;

for (const num of numbers) {
  sum += num;
}

console.log(`Sum: ${sum}`); // Sum: 150

Example 2: Find Maximum

const scores = [85, 92, 78, 95, 88];
let max = scores[0];

for (const score of scores) {
  if (score > max) {
    max = score;
  }
}

console.log(`Highest score: ${max}`); // 95

Example 3: Count Occurrences

const text = 'hello world';
let vowelCount = 0;
const vowels = 'aeiou';

for (const char of text) {
  if (vowels.includes(char)) {
    vowelCount++;
  }
}

console.log(`Vowels: ${vowelCount}`); // 3

Example 4: Build a String

const words = ['Hello', 'World', 'from', 'JavaScript'];
let sentence = '';

for (let i = 0; i < words.length; i++) {
  sentence += words[i];
  if (i < words.length - 1) {
    sentence += ' ';
  }
}

console.log(sentence); // "Hello World from JavaScript"

Example 5: FizzBuzz

Classic programming exercise:

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);
  }
}

Exercises

Exercise 1: Sum of Even Numbers

Calculate the sum of all even numbers from 1 to 20.

Solution
let sum = 0;

for (let i = 2; i <= 20; i += 2) {
  sum += i;
}

console.log(`Sum of even numbers: ${sum}`); // 110

// Alternative with condition
let sum2 = 0;
for (let i = 1; i <= 20; i++) {
  if (i % 2 === 0) {
    sum2 += i;
  }
}
console.log(`Sum (alternative): ${sum2}`); // 110

Exercise 2: Reverse Array

Print array elements in reverse order.

const colors = ['red', 'green', 'blue', 'yellow'];
Solution
const colors = ['red', 'green', 'blue', 'yellow'];

for (let i = colors.length - 1; i >= 0; i--) {
  console.log(colors[i]);
}
// Output: yellow, blue, green, red

Exercise 3: Find Element

Find the index of "banana" in the array. Print -1 if not found.

const fruits = ['apple', 'orange', 'banana', 'mango'];
Solution
const fruits = ['apple', 'orange', 'banana', 'mango'];
let index = -1;

for (let i = 0; i < fruits.length; i++) {
  if (fruits[i] === 'banana') {
    index = i;
    break;
  }
}

console.log(`Index: ${index}`); // 2

Exercise 4: Multiplication Table

Print the multiplication table for a number (1 to 10).

const number = 7;
Solution
const number = 7;

console.log(`Multiplication table for ${number}:`);
for (let i = 1; i <= 10; i++) {
  console.log(`${number} x ${i} = ${number * i}`);
}

Exercise 5: Password Validation

Check if a password contains at least one digit. Use a loop to check each character.

const password = 'secret123';
Solution
const password = 'secret123';
let hasDigit = false;

for (const char of password) {
  if (char >= '0' && char <= '9') {
    hasDigit = true;
    break;
  }
}

console.log(`Password has digit: ${hasDigit}`); // true

Key Takeaways

  1. for loops are best when you know the number of iterations
  2. for...of is the cleanest way to iterate over arrays
  3. while loops are for unknown iteration counts
  4. do...while guarantees at least one execution
  5. break exits the loop immediately
  6. continue skips to the next iteration
  7. Avoid infinite loops - ensure the condition will become false

Resources

Resource Type Description
MDN: for Documentation Official for loop reference
MDN: while Documentation Official while loop reference
JavaScript.info: Loops Tutorial Comprehensive loops tutorial

Next Lesson

You now have all the building blocks! Let's put them together in a practical project.

Continue to Lesson 1.6: Practice - Calculator