JavaScriptbeginner 7 min
Repeat code with for and while loops instead of copying and pasting.
How to repeat an action many times with a for loop and a while loop.
Printing 100 names, adding up a list of prices, retrying a request: all of these are repetition. Loops let you write the instruction once.
A for loop has three parts in its parentheses:
let i = 0.i++ (add one).A while loop repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need.
for loop starts with i = 1.1 <= 3, true, so it prints Round 1, then i++ makes i 2.Round 2 and Round 3. When i is 4, 4 <= 3 is false and the loop ends.while loop adds n to total each round: 1, 3, 6, 10, 15.n becomes 6 the condition fails, and it prints Sum 1 to 5 is 15.Change the loop so it counts from 1 to 10. Then make it print only the even numbers (hint: i % 2 === 0).
i < 3 runs 3 times starting at 0, i <= 3 runs 4 times.i++ in a while loop, which creates an infinite loop.const for the counter. The counter changes, so use let.for repeats a set number of times; while repeats until a condition fails.let for the counter.Next: packaging code into functions.
for (start; keepGoingWhile; afterEachRound) { ... }for (let i = 1; i <= 3; i++) {
console.log("Round " + i);
}
let total = 0;
let n = 1;
while (n <= 5) {
total = total + n;
n++;
}
console.log("Sum 1 to 5 is " + total);