Why Loops Exist
By the end of this lesson, you'll be able to:
- Explain the problem loops solve compared to writing repeated statements by hand
- Recognize the shape of a repeating task in a business scenario
- Preview the loop types this module covers
Prerequisites: Module 6: "Making Decisions"
The problem: repeating yourself
Imagine debugging the name of 5 accounts one at a time:
System.debug(accountNames[0]);
System.debug(accountNames[1]);
System.debug(accountNames[2]);
System.debug(accountNames[3]);
System.debug(accountNames[4]);
This works for 5. It's unworkable for 500, and it breaks the moment the list's size changes. A loop replaces all of this with one block of code that runs once per item, however many items there are.
A real business example: Logistics
List<String> trackingNumbers = new List<String>{'TRK001', 'TRK002', 'TRK003'};
for (String trackingNumber : trackingNumbers) {
System.debug('Checking status for ' + trackingNumber);
}
A logistics batch job doesn't know in advance how many shipments it needs to check — it could be 3 or 30,000. A loop handles both identically, which is exactly the point.
What this module covers
Apex gives you several loop shapes for different situations: for, the enhanced for, while, and do-while, plus break/continue for controlling a loop mid-run. The final lesson covers governor limits — the hard ceiling Salesforce places on how much looping code can do, and why it matters more here than almost anywhere else in Apex.
Exercise
In your own words (as a code comment), explain why a loop is better than writing 100 separate System.debug statements.
Show hint
Think about what happens if the number of items changes from 100 to 101.
Why Loops Exist Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A loop repeats a block of code without you writing it out by hand — essential once you're working with more than a handful of records, which is nearly always in Salesforce.