Skip to content
blog
2 min read

Mastering the Art of Loops: Running Code Efficiently

Use for loops to run code multiple times efficiently. Learn the anatomy of a for loop, how to loop through arrays, and how to avoid infinite loops.

A loop runs a block of code repeatedly. Instead of writing the same line ten times, you write it once and tell JavaScript how many times to run it.

Anatomy of a for Loop

for (let i = 0; i < 5; i++) {
console.log(i);
}
// 0, 1, 2, 3, 4

Three parts, separated by semicolons:

  • Initializer — let i = 0 — runs once before the loop starts
  • Condition — i < 5 — checked before each iteration; loop stops when false
  • Update — i++ — runs after each iteration

Looping Through Arrays

const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}

colors.length gives you the count. The loop stops when i reaches the last index.

Counting Backwards

for (let i = 3; i > 0; i--) {
console.log(i);
}
// 3, 2, 1

Infinite Loops

An infinite loop freezes the browser. It happens when the condition never becomes false:

// Don't do this
for (let i = 0; i > -1; i++) {
console.log(i); // runs forever
}

Always make sure your update moves the variable toward making the condition false.

for vs. forEach

Use for when you need the index, need to break early, or need to iterate backwards. For simple iteration, forEach or for...of is cleaner.