JS Loops
JS Loops
Loops allow you to repeat a block of code multiple times. They are commonly used when working with arrays, counters, and dynamic data.
JS Loop for
The for loop runs a block of code a specific number of times.
for (let i = 0; i < 5; i++) {
console.log(i);
}
The for loop has three parts: initialization, condition, and increment.
JS Loop while
The while loop runs as long as the condition is true.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Be careful: if the condition never becomes false, the loop will run forever.
do...while Loop
The do...while loop runs at least once, even if the condition is false.
let n = 0;
do {
console.log(n);
n++;
} while (n < 3);
JS Break
The break statement stops a loop immediately.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
JS Continue
The continue statement skips the current iteration and continues with the next one.
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
}
console.log(i);
}
JS Control Flow
Control flow statements determine how code is executed. Loops, conditions, break, and continue are all part of JavaScript control flow.
You can also loop through arrays using for...of:
const numbers = [10, 20, 30];
for (const value of numbers) {
console.log(value);
}
Use for...in when iterating over object properties:
const user = { name: "John", age: 30 };
for (const key in user) {
console.log(key, user[key]);
}
Next Step
Continue with JS Strings to learn how to work with text in JavaScript.