The for loop is the most versatile, compact, and ubiquitous loop construct in computer science. It encapsulates loop initialization, condition testing, and state incrementation into a single, clean header line.
// for (initialization; condition; afterthought)
for (let i = 0; i < 5; i++) {
console.log(`Current Index: ${i}`);
}
const technologies = ["JavaScript", "Python", "PHP", "Linux"];
for (let i = 0; i < technologies.length; i++) {
console.log(`Technology #${i + 1}: ${technologies[i]}`);
}
for (let i = 10; i >= 0; i -= 2) {
console.log(`Countdown: ${i}`); // 10, 8, 6, 4, 2, 0
}
A loop inside another loop is known as a nested loop. The inner loop completes all its iterations for every single iteration of the outer loop:
// Generating a 3x3 Coordinate Matrix
for (let row = 1; row <= 3; row++) {
let rowOutput = "";
for (let col = 1; col <= 3; col++) {
rowOutput += `[${row},${col}] `;
}
console.log(rowOutput);
}
// Output:
// [1,1] [1,2] [1,3]
// [2,1] [2,2] [2,3]
// [3,1] [3,2] [3,3]
Classic Exam Problem: "Print a right-angled star pyramid pattern of height N using nested loops."
function printStarPyramid(height) {
for (let i = 1; i <= height; i++) {
let stars = "";
for (let j = 1; j <= i; j++) {
stars += "* ";
}
console.log(stars);
}
}
printStarPyramid(4);
// *
// * *
// * * *
// * * * *
What modern ES6 loops make iterating over objects and arrays 10x cleaner? Proceed to: JavaScript For..In vs For..Of Loops →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Iterating over object keys and array values.
Modern functional iteration alternatives.
Managing loop control flow.
Indefinite vs definite iteration.