Let’s harness the power of repetition by using loops! Loops allow you to execute code repeatedly without writing the same statements over and over. Instead of manually processing each item in a collection or repeating an action, loops automate this work for you.
// Without loops - repetitive and inflexible
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
// With a loop - clean and scalable
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Loops are essential for processing arrays, generating repeated output, waiting for conditions to be met, and handling any scenario where you need to repeat an action multiple times. They're one of the fundamental building blocks of programming logic.
<aside> 💡
Loops save you from writing repetitive code. If you find yourself copying and pasting similar code with slight variations, there's probably a loop that can handle it better.
</aside>
https://www.youtube.com/watch?v=s9wW2PpJsmQ
for loopThis one’s a classic: the for loop. This loop gives you precise control over iteration. It's structured in three parts: initialization, condition, and increment.
// Basic syntax
for (initialization; condition; increment) {
// code to execute
}
// Example: print numbers 0 to 4
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// Iterate through an array
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
console.log(`Color ${i}: ${colors[i]}`);
}
// Color 0: red
// Color 1: green
// Color 2: blue
// Count backwards
for (let i = 10; i >= 0; i--) {
console.log(i);
}
// Skip by 2
for (let i = 0; i < 10; i += 2) {
console.log(i); // 0, 2, 4, 6, 8
}
There are three parts of a for loop:
let i = 0): Runs once before the loop startsi < 5): Checked before each iteration, loop continues while truei++): Runs after each iteration<aside> ⌨️
Create an array of 5 numbers. Write a for loop that calculates and prints the sum of all numbers.
</aside>
for...of loopThe for...of loop iterates directly over array values, making code cleaner when you don't need the index:
const fruits = ['apple', 'banana', 'orange'];
// for...of (direct access to values)
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// orange
// More readable than traditional for loop
const scores = [85, 92, 78, 95];
let total = 0;
for (const score of scores) {
total += score;
}
console.log(`Average: ${total / scores.length}`); // Average: 87.5
// Works with strings too
const word = 'Hello';
for (const letter of word) {
console.log(letter); // H, e, l, l, o
}
<aside> 💡
for...of is the modern, readable way to loop through arrays. It's perfect when you care about the values, not their positions.
</aside>
Use for...of when you need the values themselves. Use a traditional for loop when you need the index position.
// When you need the index, use traditional for
for (let i = 0; i < fruits.length; i++) {
console.log(`${i + 1}. ${fruits[i]}`);
}
// 1. apple
// 2. banana
// 3. orange
// When you only need values, use for...of
for (const fruit of fruits) {
console.log(`I like ${fruit}`);
}
<aside> 💡
Modern JavaScript keeps getting more readable. for...of lets you write loops that read almost like plain English, making your code easier for others (and future you) to understand.
</aside>
for...in loopThe for...in loop iterates over object keys (property names). While it can technically work with arrays, it's primarily designed for objects:
const person = {
name: 'Alice',
age: 28,
city: 'Amsterdam'
};
// Iterate over object properties
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// name: Alice
// age: 28
// city: Amsterdam
// Practical example: build a query string
const params = {
search: 'javascript',
page: 2,
limit: 10
};
let queryString = '?';
for (const key in params) {
queryString += `${key}=${params[key]}&`;
}
console.log(queryString); // ?search=javascript&page=2&limit=10&
while LoopThe while loop continues executing as long as its condition is true. Unlike for loops, it doesn't have built-in initialization or increment, you need to manage those yourself:
// Basic syntax
while (condition) {
// code to execute
}
// Example: count to 5
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// 0, 1, 2, 3, 4
// Process items until array is empty
const tasks = ['email', 'meeting', 'code review'];
while (tasks.length > 0) {
const task = tasks.pop();
console.log(`Completed: ${task}`);
}
// Completed: code review
// Completed: meeting
// Completed: email
Use while loops when you don't know in advance how many iterations you'll need. For example, when waiting for user input, processing until a condition changes, or working with dynamic data.
<aside> ⌨️
Write a while loop that starts at 100 and counts down by 10, printing each number, until it reaches 0.
</aside>
Be careful with while loops! If the condition never becomes false, you will create an infinite loop that can freeze your browser or application. Always ensure the condition will eventually become false.
// INFINITE LOOP, DON'T RUN THIS!
let x = 0;
while (x < 10) {
console.log(x);
// Forgot to increment x, it loops forever!
}
// CORRECT VERSION
let y = 0;
while (y < 10) {
console.log(y);
y++; // Condition will eventually become false
}
break & continueThe break statement immediately exits the current loop, regardless of the condition. Use break when you've found what you're looking for or when continuing the loop would be wasteful or incorrect.
// Find first even number
const numbers = [1, 3, 5, 8, 9, 10];
for (const num of numbers) {
if (num % 2 === 0) {
console.log(`Found even number: ${num}`);
break; // Stop looking once we find one
}
}
// Found even number: 8
// Search with traditional for loop
const users = ['Alice', 'Bob', 'Charlie', 'David'];
let found = false;
for (let i = 0; i < users.length; i++) {
if (users[i] === 'Charlie') {
console.log(`Found at index ${i}`);
found = true;
break;
}
}
// Exit while loop when condition met
let password;
let tries = 0;
while (tries < 3) {
password = prompt('Enter password:');
if (password === 'secret123') {
console.log('Access granted!');
break; // Exit loop early on success
}
tries++;
}
The continue statement skips the rest of the current iteration and moves to the next one. Use continue when you want to skip certain items but keep processing the rest (it's often clearer than wrapping the entire loop body in an if statement).
Different loops serve different purposes. Here's when to use each:
Use for...of when:
Use traditional for when:
Use for...in when:
Use while when:
<aside> ⌨️
Create an array of numbers from 1 to 20. Use different loops to: (1) print all even numbers using for...of with continue, (2) find the first number divisible by 7 using for with break, and (3) sum all numbers using while.
</aside>
The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **
