Step 1 of 7 · Reading · ~3 min
Learn
Control Flow
Loops: for and while
A loop repeats a block of code. By the end of this lesson you can pick the right loop for a job, keep running totals and counters correctly, and stop a loop that would otherwise never end.
The for loop
Use for when you know how many times to repeat, or you are counting.
The three parts in the parentheses, separated by semicolons:
- Start (
let i = 1) runs once, before anything else. - Condition (
i <= 4) is checked before every pass; when it is false the loop ends. - Step (
i++, short fori = i + 1) runs after every pass.
Count the passes: starting at 1 and testing i <= 4 runs 4 times; testing i < 4 would run 3. Mixing up < and <= is the classic off-by-one error.
The while loop
Use while when you cannot say in advance how many passes it will take: you only know when to stop.
Something inside the body must move the condition toward false. If n never changed, the loop would run forever and your program would be stopped by the time limit.
do { ... } while (condition); is the same loop with the check at the bottom, so the body always runs at least once.
Accumulators and counters
Most loops build something up across passes. Declare the variable with let before the loop, update it inside, and use it after the loop:
Printing inside the loop gives one line per pass; printing after it gives one result. Keep an eye on which one you want. To track a maximum, update it only when the current value beats it: if (value > best) { best = value; }, and start best from a value that already counts, not from 0.
for...of
for (const item of collection) visits each value in turn, with no counter to manage. It works on strings (and on arrays, which a later lesson covers):
break and continue
break leaves the loop immediately; continue skips to the next pass.
Choosing
- Counting, or you need the index:
for. - Going through every character or value:
for...of. - Repeat until something happens, with an unknown number of passes:
while.
Common mistakes
- Off-by-one:
i < nwhen the last valuenshould be included. - A
whilewhose condition never changes: infinite loop and a timeout. - Declaring the accumulator inside the loop, so it resets to its starting value on every pass.
- Printing inside the loop when only the final result is wanted.
- Starting a running maximum at 0: for all-negative data the answer stays 0.
Your exercise
Simulate a number sequence whose length you cannot predict, which is exactly what while is for. The starter reads the start value and declares the counters; you write the loop.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…