Introduction
Loops help repeat actions many times without writing the same code again and again.
Loops help repeat actions many times without writing the same code again and again.
for (initialization; condition; update) { // code to repeat } // or while (condition) { // code to repeat // update step inside }
Initialization runs once at the start.
Condition is checked before each loop; if false, loop stops.
for (let i = 0; i < 3; i++) { console.log(i); }
let count = 0; while (count < 3) { console.log(count); count++; }
This program repeats a greeting 5 times, showing the step number each time.
for (let i = 1; i <= 5; i++) { console.log(`Step ${i}: Hello!`); }
Loops check the condition before running the code inside each time.
If the condition is false at the start, the loop code never runs.
Be careful to update variables inside the loop to avoid endless loops.
Loops repeat code while a condition is true.
Use for loops when you know how many times to repeat.
Use while loops when you repeat until a condition changes.
for loop do in JavaScript?for loop is designed to repeat code multiple times based on a condition.for loop behavior.for loop in JavaScript?for (initialization; condition; increment) { }.for (let i = 0; i < 5; i++) { } matches the correct syntax with let i = 0; i < 5; i++.let sum = 0;
for (let i = 1; i <= 3; i++) {
sum += i;
}
console.log(sum);for (let i = 0; i < 5; i--) {
console.log(i);
}i--, so i decreases each time starting from 0.i < 5, which is true for all i less than 5, including negative numbers. Since i decreases, it never reaches 5 or more, so loop never ends.let count = 0;
let i = 10;
while (i > 0) {
i -= 3;
count++;
}
console.log(count);Pass the test and this pattern moves unknown