Week 3
Control Flow
JavaScript Loops
Learn how to repeat actions with loops!
Learning Objectives
- Master for loops
- Understand while and do-while loops
- Learn when to use different types of loops
Explanation
Loops allow you to execute a block of code multiple times. They're essential for tasks like processing arrays, repeating actions, or running code until a condition is met.
JavaScript has several types of loops:
1. for loop:
The most common loop, with a clear structure for initialization, condition, and increment/decrement.
Syntax: for (initialization; condition; update) { code block }
2. while loop:
Executes a block of code as long as a condition is true.
Syntax: while (condition) { code block }
3. do-while loop:
Similar to the while loop, but always executes the block of code at least once before checking the condition.
Syntax: do { code block } while (condition);
4. for...of loop:
A modern way to loop through the values in an array or other iterable objects.
Syntax: for (let element of array) { code block }
5. for...in loop:
Used to loop through the properties of an object.
Syntax: for (let property in object) { code block }
Important loop control statements:
- break: Exits the loop immediately
- continue: Skips the current iteration and moves to the next one
Code Example
// For loop for (let i = 0; i < 5; i++) { console.log("Iteration #" + i); // Outputs numbers 0 through 4 } // While loop let count = 0; while (count < 5) { console.log("Count: " + count); count++; } // Do-while loop let num = 0; do { console.log("Num: " + num); num++; } while (num < 5); // For...of loop (for arrays) let planets = ["Mercury", "Venus", "Earth", "Mars"]; for (let planet of planets) { console.log("Planet: " + planet); } // For...in loop (for objects) let person = { name: "Rey", age: 19, planet: "Jakku" }; for (let property in person) { console.log(property + ": " + person[property]); } // Break statement for (let i = 0; i < 10; i++) { if (i === 5) { break; // Exit the loop when i is 5 } console.log(i); } // Continue statement for (let i = 0; i < 10; i++) { if (i === 5) { continue; // Skip iteration when i is 5 } console.log(i); }
Try It Yourself!
Write a loop that counts from 10 down to 1, then outputs 'Blast off!'
JavaScript Editor
Mini Quiz
Test your knowledge with these quick questions!
1. Which loop always executes at least once?
for loop
while loop
do-while loop
for-in loop
2. What does the continue statement do in a loop?
It stops the loop completely
It skips the current iteration and continues with the next one
It continues the loop indefinitely
It pauses the loop for a moment
Your Progress
Lesson ProgressIn Progress
Est. time: 15-20 min
100 points
Module Progress
JavaScript Fundamentals2/10 completed
Complete all lessons to earn the Code Fundamentalist badge!
Rewards
Complete this lesson
Earn 100 points
Complete this module
Earn the Code Fundamentalist badge