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.
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.
for (let i = 0; i < 5; i++) { console.log(i);}// 0, 1, 2, 3, 4Three parts, separated by semicolons:
let i = 0 — runs once before the loop startsi < 5 — checked before each iteration; loop stops when falsei++ — runs after each iterationconst 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.
for (let i = 3; i > 0; i--) { console.log(i);}// 3, 2, 1An infinite loop freezes the browser. It happens when the condition never becomes false:
// Don't do thisfor (let i = 0; i > -1; i++) { console.log(i); // runs forever}Always make sure your update moves the variable toward making the condition false.
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.