Lesson · JavaScript Basics
Loops and iteration
Iteration applies the same operation to several values without duplicating statements.
What you will learn
- Iterate over an array with for...of
- Use a while loop safely
- Understand the loop's stopping condition
Process each item
A for...of loop visits each value in an iterable such as an array. The loop variable receives the current value on each pass. This is often clearer than managing a numeric index when the task only needs the values themselves.
Repeat while a condition holds
A while loop checks its condition before each pass. Update the state that controls the condition inside the loop, or the program may never stop. Start with a small example and trace the condition before and after one iteration.
Avoid unnecessary complexity
Use a loop when each item needs a step-by-step operation, and consider array methods when a transformation or filter is the clearest expression. Do not nest loops just because the syntax allows it; first identify which collection each loop traverses.
Keep side effects visible
A loop may update totals, append values, or display output. Give that change a clear purpose and avoid mutating the collection being traversed unless the behavior is deliberate. A predictable loop has an obvious input, action, and stopping rule.
Choose where a loop can stop
break exits a loop and continue skips to its next pass. Both can be useful when the task has a clear early exit, but too many jumps make the control flow hard to follow. If you need a loop counter, update it in one obvious place and test the condition at its starting and ending values.
const topics = ['HTML', 'CSS', 'JavaScript'];
for (const topic of topics) {
console.log(topic);
}
Expected output
HTML
CSS
JavaScript
Practice exercise
Loop through three numbers and print each number doubled.
Show a hint
Use for...of and multiply the current value by 2.
Show one possible solution
For each number in an array, log number * 2 inside a for...of loop.
Quick check
for...of directly gives each item in an iterable.