Standard For Loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i + 1}`);
}
For...of Loop (Iterating over Arrays)
const fruits = ['apple', 'banana', 'orange'];
for (const fruit of fruits) {
console.log(fruit);
For...in Loop (Iterating over Object Properties)
const person = {
name: 'John',
age: 30,
job: 'Developer'
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
forEach Loop (Array Method)
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index) => {
console.log(`Index ${index}: ${number}`);
});
While Loop (Not technically a for loop, but worth mentioning)
let count = 0;
while (count < 3) {
console.log(`Count: ${count}`);
count++;
}
These examples demonstrate various ways to iterate in JavaScript, each suited for different scenarios and data structures.
Top comments (0)