Home Courses For Loop Explained in Depth

For Loop Explained in Depth

  1. The for loop is the most commonly used loop in JavaScript
  2. It is used when the number of iterations is known


Syntax of For Loop


for (initialization; condition; increment/decrement) {
// code to repeat
}

Breakdown:

  1. Initialization → Starting point (e.g., let i = 0)
  2. Condition → Loop runs until this is true
  3. Increment/Decrement → Updates value after each iteration


Basic Example


for (let i = 0; i <= 10; i++) {
console.log(i);
}

Output:

0 to 10

Important:

  1. <= 10 → includes 10
  2. < 10 → stops at 9


Understanding Off-by-One Concept


for (let i = 0; i <= 10; i++)

  1. Runs 11 times (0 to 10)

for (let i = 0; i < 10; i++)

  1. Runs 10 times (0 to 9)


Starting from Different Values


for (let i = 5; i <= 10; i++) {
console.log(i);
}

Output:

5 6 7 8 9 10


Increment by More Than 1

Increment by 2:


for (let i = 0; i <= 10; i += 2) {
console.log(i);
}

Output:

0 2 4 6 8 10

Increment by 3:


for (let i = 1; i <= 10; i += 3) {
console.log(i);
}


Reverse Loop (Decrement)


for (let i = 10; i >= 0; i--) {
console.log(i);
}

Output:

10 9 8 ... 0


Nested Loops

  1. A loop inside another loop

Example:


for (let i = 0; i <= 3; i++) {
for (let j = 0; j <= 2; j++) {
console.log("j:", j);
}
console.log("-----");
}

Key Point:

  1. Inner loop runs completely for each iteration of outer loop


Important Rule for Nested Loops

  1. Use different variables (i, j)
  2. Avoid using same variable → can cause bugs or infinite loops


Printing Tables Using For Loop

Example: Table of 10


for (let i = 1; i <= 10; i++) {
console.log(10 * i);
}

Example: Table of 34


for (let i = 1; i <= 10; i++) {
console.log(34 * i);
}


Share this lesson: