Classic C-style loop; best when you know exactly how many times you want to run.
for (initialization; condition; update) {
// code block
}Useful for looping until a condition is no longer true.
while (condition) {
// code block
}This loop ensures the body runs at least once before checking the condition.
do {
// code block
} while (condition)Preferred for looping through arrays and strings.
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}Use for...in when you need to access object keys. Always use keyof for safe typing.
const user = { name: "Alex", age: 30 };
for (const key in user) {
console.log(key, user[key as keyof typeof user]);
}continue skips the current loop iteration, break exits the loop.
for (let i = 0; i < 5; i++) {
if (i === 3) continue;
if (i === 4) break;
console.log(i);
}Output:
0
1
2for...of for array iteration.break sparingly for clean logic.Ask the AI if you need help understanding or want to dive deeper in any topic