Loops are one of the most powerful tools in programming. They allow you to execute a block of code repeatedly without writing it multiple times. Whether you need to process a list of items, wait for a condition, or repeat an action a specific number of times, loops make it possible.
Imagine you need to print numbers 1 to 100:
// ❌ Without loops — tedious and error-prone
console.log(1);
console.log(2);
console.log(3);
// ... 97 more lines!
// ✅ With a loop — clean and scalable
for (let i = 1; i <= 100; i++) {
console.log(i);
}JavaScript provides several ways to loop:
forloop — loop with initialization, condition, and incrementwhileloop — loop while a condition is truedo...whileloop — loop at least once, then check conditionfor...ofloop — iterate over iterable values (arrays, strings, etc.)for...inloop — iterate over object keys
The most common loop. Perfect when you know how many times to iterate.
for (initialization; condition; increment) {
// code to repeat
}for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4Step by step:
let i = 0— Initialize counteri < 5— Check condition (true? continue; false? exit)console.log(i)— Execute loop bodyi++— Increment counter- Go back to step 2
// Count from 1 to 10
for (let i = 1; i <= 10; i++) {
console.log(i);
}
// Countdown from 10 to 1
for (let i = 10; i >= 1; i--) {
console.log(i);
}
// Count by 2s
for (let i = 0; i <= 10; i += 2) {
console.log(i); // 0, 2, 4, 6, 8, 10
}
// Skip every other number with custom increment
for (let i = 1; i <= 20; i += 3) {
console.log(i); // 1, 4, 7, 10, 13, 16, 19
}for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i=${i}, j=${j}`);
}
}
// Output:
// i=1, j=1
// i=1, j=2
// i=1, j=3
// i=2, j=1
// ... and so onRepeats while a condition is true. Use when you don't know how many iterations you need.
while (condition) {
// code to repeat
}// Count to 5
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
// User input simulation (loop until valid input)
let password = "";
while (password !== "secret") {
password = "secret"; // In real code, this would be user input
}
console.log("Access granted!");
// Find first number divisible by 7 and 13
let num = 1;
while (true) {
if (num % 7 === 0 && num % 13 === 0) {
console.log(num); // 91
break;
}
num++;
}// ❌ This will run forever!
while (true) {
console.log("Help! I'm stuck!");
}
// ❌ Counter never changes
let i = 0;
while (i < 10) {
console.log(i);
// Forgot to increment i!
}Always ensure your loop has a way to terminate!
Similar to while, but the body executes at least once before checking the condition.
do {
// code to repeat
} while (condition);let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
// Output: 1, 2, 3, 4, 5let num = 10;
// while loop — body never executes
while (num < 5) {
console.log("while: " + num);
}
// do...while loop — body executes once
do {
console.log("do...while: " + num);
} while (num < 5);
// Output: "do...while: 10"Use
do...whenwhen you need the code to run at least once (e.g., menu systems).
Iterates over values of an iterable (arrays, strings, Maps, Sets, etc.). Introduced in ES6.
for (const item of iterable) {
// use item
}const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// cherryconst word = "Hello";
for (const char of word) {
console.log(char);
}
// H, e, l, l, oconst colors = ["red", "green", "blue"];
for (const [index, color] of colors.entries()) {
console.log(`${index}: ${color}`);
}
// 0: red
// 1: green
// 2: blueIterates over keys (property names) of an object. Do not use with arrays — use for...of or regular for instead.
for (const key in object) {
// use key and object[key]
}const person = {
name: "Alice",
age: 25,
city: "New York"
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// name: Alice
// age: 25
// city: New Yorkconst arr = ["a", "b", "c"];
// It works, but...
for (const index in arr) {
console.log(index); // "0", "1", "2" — strings, not numbers!
}
// It also iterates over custom properties
arr.customProp = "oops";
for (const index in arr) {
console.log(index); // "0", "1", "2", "customProp" — unexpected!
}Rule of thumb:
for...infor objects,for...offor arrays.
Immediately terminates the loop:
for (let i = 1; i <= 100; i++) {
if (i === 5) {
break; // Exit the loop completely
}
console.log(i); // 1, 2, 3, 4
}Skips the rest of the current iteration and moves to the next:
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // 1, 3, 5, 7, 9
}Label loops to break or continue an outer loop from an inner one:
outerLoop: for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (i === 2 && j === 2) {
break outerLoop; // Breaks the outer loop, not just inner
}
console.log(`i=${i}, j=${j}`);
}
}| Loop | Best For | Know Iterations? | Access |
|---|---|---|---|
for |
Counting, indexing | Yes | Index-based |
while |
Unknown iterations | No | Manual control |
do...while |
At least once | No | Manual control |
for...of |
Array/string values | Yes | Direct values |
for...in |
Object properties | Yes | Keys only |
const numbers = [10, 20, 30, 40, 50];
let sum = 0;
for (const num of numbers) {
sum += num;
}
console.log(sum); // 150const scores = [45, 82, 67, 91, 55];
let max = scores[0];
for (let i = 1; i < scores.length; i++) {
if (scores[i] > max) {
max = scores[i];
}
}
console.log(max); // 91const original = [1, 2, 3, 4, 5];
const reversed = [];
for (let i = original.length - 1; i >= 0; i--) {
reversed.push(original[i]);
}
console.log(reversed); // [5, 4, 3, 2, 1]const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = [];
for (const num of numbers) {
if (num % 2 === 0) {
evens.push(num);
}
}
console.log(evens); // [2, 4, 6, 8, 10]// ❌ Prints undefined for the last element
const arr = ["a", "b", "c"];
for (let i = 0; i <= arr.length; i++) {
console.log(arr[i]); // a, b, c, undefined
}
// ✅ Correct: use < not <=
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]); // a, b, c
}// ❌ Skips elements!
const nums = [1, 2, 3, 4, 5];
for (let i = 0; i < nums.length; i++) {
if (nums[i] % 2 === 0) {
nums.splice(i, 1); // Removes element, shifts others!
}
}
console.log(nums); // [1, 3, 5] — but wait, did we check all?
// ✅ Better: iterate backwards
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] % 2 === 0) {
nums.splice(i, 1);
}
}// ❌ Error: can't reassign const
for (const i = 0; i < 5; i++) {
console.log(i);
}
// ✅ Use let
for (let i = 0; i < 5; i++) {
console.log(i);
}
// ✅ But const is fine in for...of
for (const num of [1, 2, 3]) {
console.log(num);
}// ❌ Might never equal exactly 1.0 due to floating point
for (let i = 0; i !== 1; i += 0.1) {
console.log(i); // Runs forever!
}
// ✅ Use < or > for floats
for (let i = 0; i < 1; i += 0.1) {
console.log(i.toFixed(1));
}Print the multiplication table for a given number:
// Input: 5
// Output:
// 5 × 1 = 5
// 5 × 2 = 10
// ...
// 5 × 10 = 50Calculate factorial using a loop:
function factorial(n) {
// Return n! using a loop
}
console.log(factorial(5)); // 120Print all prime numbers between 1 and 100.
Print this pattern:
*
**
***
****
*****
Then print:
*
***
*****
*******
*********
Given an array of numbers, calculate:
- Sum
- Average
- Minimum
- Maximum
- Count of even numbers
All using loops (no built-in array methods).
for: Best when you know the number of iterationswhile: Best when iterations depend on a dynamic conditiondo...while: Best when the body must run at least oncefor...of: Best for iterating array/string valuesfor...in: Best for iterating object keys (avoid with arrays)break: Exits a loop immediatelycontinue: Skips to the next iteration- Always ensure loops have a termination condition
After mastering loops, learn about:
- Arrays — storing and manipulating collections
- Functions — organizing code into reusable blocks
- Problem Solving with Loops — applying loops to real problems
Happy coding! 🚀