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: "Lists: A Quick Foundation Before Looping"
The problem: repeating yourself
Imagine debugging the name of every account in this List, one at a time:
List<String> accountNames = new List<String>{'Acme Corp', 'Globex', 'Initech', 'Umbrella Corp', 'Soylent Co'};
System.debug(accountNames[0]);
System.debug(accountNames[1]);
System.debug(accountNames[2]);
System.debug(accountNames[3]);
System.debug(accountNames[4]);
List<String> accountNames = new List<String>{...};— five accounts.- (blank line)
3-7.
System.debug(accountNames[0]);throughSystem.debug(accountNames[4]);— one hand-written line per item, by index.
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);
}
List<String> trackingNumbers = new List<String>{...};— three tracking numbers.- (blank line)
for (String trackingNumber : trackingNumbers) {— a loop (covered fully starting next lesson) that runs once per item in the List, automatically.System.debug('Checking status for ' + trackingNumber);— runs once for each tracking number in turn.}— closes the loop.
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
Leaderboard
- 1. Monde Masiza 1/1
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.