Loops in JavaScript
Loops let you repeat code multiple times. JavaScript has several loop types for different situations.
for Loop
The most common loop. Repeats code a specific number of times:
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
Anatomy
for (initialization; condition; increment) {
// Code to repeat
}
- initialization: runs once at start
- condition: checked before each iteration
- increment: runs after each iteration
Examples
// Count from 1 to 10
for (let i = 1; i <= 10; i++) {
console.log(i);
}
// Count backwards
for (let i = 10; i > 0; i--) {
console.log(i);
}
// Skip numbers
for (let i = 0; i < 20; i += 5) {
console.log(i); // 0, 5, 10, 15
}
while Loop
Repeats while a condition is true:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Output: 0, 1, 2, 3, 4
When to Use
Use while when you don’t know how many iterations you need:
let password = "";
while (password !== "secret") {
password = prompt("Enter password:");
}
console.log("Access granted!");
do…while Loop
Runs at least once, then checks condition:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
// Output: 0, 1, 2, 3, 4
Difference from while
// while - condition checked first
let x = 10;
while (x < 5) {
console.log(x); // Never runs
}
// do...while - runs at least once
let y = 10;
do {
console.log(y); // Runs once
} while (y < 5);
for…of Loop
Iterates over values in an iterable (array, string, etc.):
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
// Output: red, green, blue
With Strings
const word = "hello";
for (const letter of word) {
console.log(letter);
}
// Output: h, e, l, l, o
With Sets
const numbers = new Set([1, 2, 3, 2, 1]);
for (const num of numbers) {
console.log(num);
}
// Output: 1, 2, 3
for…in Loop
Iterates over property names (keys) in an object:
const person = {
name: "Alice",
age: 30,
city: "New York"
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output:
// name: Alice
// age: 30
// city: New York
for…in vs for…of
const arr = ["a", "b", "c"];
// for...in - gets indices (keys)
for (const index in arr) {
console.log(index); // 0, 1, 2
}
// for...of - gets values
for (const value of arr) {
console.log(value); // a, b, c
}
break Statement
Exit a loop early:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit loop
}
console.log(i);
}
// Output: 0, 1, 2, 3, 4
Practical Example
function findNumber(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
console.log(`Found at index ${i}`);
break;
}
}
}
findNumber([10, 20, 30, 40], 30); // Found at index 2
continue Statement
Skip to the next iteration:
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skip this iteration
}
console.log(i);
}
// Output: 0, 1, 3, 4
Practical Example
const numbers = [1, 2, 3, 4, 5, 6];
for (const num of numbers) {
if (num % 2 === 0) {
continue; // Skip even numbers
}
console.log(num); // 1, 3, 5
}
Nested Loops
Loops inside loops:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i},${j}`);
}
}
// Output:
// 1,1 1,2 1,3
// 2,1 2,2 2,3
// 3,1 3,2 3,3
Creating a Multiplication Table
for (let i = 1; i <= 5; i++) {
let row = "";
for (let j = 1; j <= 5; j++) {
row += (i * j).toString().padStart(3);
}
console.log(row);
}
Practical Examples
Sum Array Elements
const numbers = [10, 20, 30, 40, 50];
let sum = 0;
for (const num of numbers) {
sum += num;
}
console.log(sum); // 150
Find Maximum Value
const scores = [45, 89, 23, 92, 67];
let max = scores[0];
for (const score of scores) {
if (score > max) {
max = score;
}
}
console.log(max); // 92
Count Occurrences
const word = "mississippi";
let count = 0;
for (const letter of word) {
if (letter === "s") {
count++;
}
}
console.log(count); // 4
Generate Pattern
for (let i = 1; i <= 5; i++) {
console.log("*".repeat(i));
}
// Output:
// *
// **
// ***
// ****
// *****
Loop Performance Tips
Use const in for…of
// Good - const prevents accidental reassignment
for (const item of items) {
console.log(item);
}
// Avoid - let allows reassignment
for (let item of items) {
console.log(item);
}
Avoid Infinite Loops
// Bad - infinite loop!
// while (true) {
// console.log("This never stops");
// }
// Good - has exit condition
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
Cache Array Length
// Good - length calculated once
const arr = [1, 2, 3, 4, 5];
const len = arr.length;
for (let i = 0; i < len; i++) {
console.log(arr[i]);
}
// Less efficient - length checked each iteration
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Summary
- for: repeat specific number of times
- while: repeat while condition is true
- do…while: run at least once, then check condition
- for…of: iterate over values
- for…in: iterate over keys
- break: exit loop early
- continue: skip to next iteration
- Nested loops: loops inside loops
Related Resources
Official Documentation
- MDN: for Statement
- MDN: while Statement
- MDN: do…while Statement
- MDN: for…of Statement
- MDN: for…in Statement
Next Steps
- JavaScript Arrays: Creation, Indexing, Methods
- Array Methods: map, filter, reduce, forEach
- JavaScript Objects: Creation, Properties, Methods
Comments