Example 1 — Loop an array by index
Read each element with colors[i].
JavaScript
const colors = ["red", "green"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
} How It Works
- length is 2.
- Indexes 0 and 1 print.
A classic for loop has three parts: start a counter, check a condition before each pass, then update the counter. Use it when you know how many times to repeat.
for (let i = 0; i < 3; i++) {
console.log(i);
} Read each element with colors[i].
const colors = ["red", "green"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
} Accumulate in a variable.
let sum = 0;
for (let i = 1; i <= 4; i++) sum += i;
console.log(sum); Exit the loop immediately.
for (let i = 0; i < 10; i++) {
if (i === 2) break;
console.log(i);
} CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful