When you need a loop and when you do not
If a task repeats over data, you probably need iteration.
Processing carts, looping through messages, summing daily sales, validating inputs or generating reports all share the same trait: a sequence of elements to inspect or transform.
If you only need a one-time check, an `if` may be enough. If you need to repeat an operation many times, that is where loops enter the picture.
for
Ideal when you know how many times you need to iterate.
- Loop through arrays by index
- Generate numeric ranges
while
Useful when the condition controls the process.
- Retry until success
- Read until a valid value appears
break
Stop execution before the loop naturally finishes.
- Exit once a value is found
- Cut an unnecessary search short
continue
Skip specific iterations.
- Ignore invalid values
- Filter without extra structures