Scalable Business for Startups
Get the oars in the water and start rowing. Execution is the single biggest factor in achievement so the faster and better your execution.
Chapter 6: Loops and Iteration in JavaScript
Learn to master different looping mechanisms in JavaScript to iterate over data effectively.
Introduction
Loops allow us to repeat code execution without redundancy, making it easier to handle large data sets.
This chapter will cover the primary types of loops in JavaScript: for
, while
, and do...while
,
as well as array-specific methods like forEach
and map
.
1. The for
Loop
The for
loop is commonly used when the number of iterations is known.
Syntax of for
Loop
for (initialization; condition; increment) {
// Code to execute in each loop iteration
}
Examples
Basic Counter: Display numbers from 1 to 10.
for (let i = 1; i <= 10; i++) {
console.log(i);
}
Summing Array Elements:
let numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log("Sum:", sum);
Looping through an Object Array:
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
];
for (let i = 0; i < users.length; i++) {
console.log(users[i].name);
}
Nested Loops:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
2. The while
Loop
The while
loop runs as long as the specified condition is true, ideal for cases where iterations aren't predetermined.
Syntax of while
Loop
while (condition) {
// Code to execute in each loop iteration
}
Examples
Countdown Timer:
let count = 10;
while (count > 0) {
console.log(count);
count--;
}
User Input Validation:
let password;
while (password !== "secure") {
password = prompt("Enter your password:");
}
3. The do...while
Loop
The do...while
loop is similar to while
, but guarantees at least one execution.
Syntax of do...while
Loop
do {
// Code to execute
} while (condition);
Examples
Simple Counter:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
4. Iteration with Array Methods
JavaScript provides powerful array iteration methods like forEach
, map
, and reduce
.
forEach
let names = ["Alice", "Bob", "Charlie"];
names.forEach(name => console.log(name));
map
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
Summary
This chapter covers the various looping mechanisms and when to use each. Traditional loops differ from array methods like forEach
and map
, giving more options for handling different scenarios in JavaScript.
Practice Exercises
- Write a program to display even numbers from 1 to 100 using a
for
loop. - Use a
while
loop to reverse a given number. - Implement a function using
reduce
to calculate the factorial of a number.