PROGRAMMING-CONCEPTS

Iteration Patterns: Definition, Purpose, and Examples

Iteration patterns describe all the ways a programming language lets you loop through collections of data. Different languages offer different tools—like for…of in JavaScript, comprehensions in Python, and iterator protocols across multiple environments—each designed to express “go through each item” in a clear and predictable way.

Knowing the strengths of each pattern helps you pick the most readable and efficient approach for the task.


Iterables and Iterators

Before looking at loops, it helps to understand iterables and iterators.

Iterable

A value you can iterate over (arrays, strings, maps, sets, lists, tuples, etc.)

Iterator

An object that produces items one by one.


JavaScript Iterable Example

const message = "hey";
const iterator = message[Symbol.iterator]();

iterator.next();
iterator.next();
iterator.next();

The iterator returns each character step by step, showing how iteration works behind the scenes. Every next() call produces { value, done }, so loops don’t need to worry about the mechanics manually.

Python Iterator Example

numbers = [1, 2, 3]
it = iter(numbers)

next(it)
next(it)

iter() returns an iterator over the list, and next() retrieves one element at a time. Python’s for loop uses this behavior internally.


for…of vs for…in (JavaScript and TypeScript)

These two keywords look similar but behave very differently.


for…of — Iterate Over Values

const fruits = ["kiwi", "mango", "plum"];

for (const fruit of fruits) {
  console.log(fruit);
}

This prints the values of the array in order. It’s the preferred choice for looping through arrays, strings, sets, and other iterable structures.


for…in — Iterate Over Keys/Indexes

const product = { id: 5, name: "Lamp" };

for (const key in product) {
  console.log(key, product[key]);
}

This iterates over object keys rather than values. It’s meant for objects, not arrays, because array order is not guaranteed with for…in.


Why They Shouldn’t Be Mixed Up

  • for…of → values (best for arrays/strings)
  • for…in → keys (best for objects)

Accidentally using for…in on arrays often leads to unexpected behavior because it returns indexes as strings rather than elements.


Modern JavaScript Iteration Patterns

Beyond the two loops above, modern JavaScript uses iterators in other common structures.

forEach

letters.forEach(l => console.log(l.toUpperCase()));

This runs a function for each item, useful for side effects like logging or DOM updates. It does not return a value and cannot be stopped early.


map, filter, reduce (Functional Iteration)

const scores = [8, 3, 9];

const doubled = scores.map(n => n * 2);

map, filter, and reduce express iteration through transformations rather than manual loops. They produce new values instead of mutating state directly.


Iterating Over Maps and Sets

const ids = new Set([1, 2, 3]);
for (const id of ids) console.log(id);

const roles = new Map([["admin", true]]);
for (const [role, active] of roles) console.log(role, active);

Sets give you values; Maps give you key/value pairs. These structures rely on standardized iterators.


Iteration in Python

Python provides one of the cleanest iteration models. It relies heavily on iterables and uses comprehensions for concise expressions.


Basic Python for-loop

items = ["pen", "cup", "book"]

for item in items:
    print(item)

This retrieves the actual values, not indexes. Python hides the mechanics and keeps iteration readable.


Python Enumeration

tasks = ["clean", "shop", "cook"]

for index, task in enumerate(tasks):
    print(index, task)

enumerate() pairs each item with its index. This avoids the need for manual counter variables.


Python Comprehensions

Comprehensions provide a compact way to build lists, sets, and dictionaries through iteration.


List Comprehension

nums = [1, 2, 3, 4]
squares = [n * n for n in nums]

This expresses “square each number” in one readable line. It combines iteration and transformation into a single expression.


Filtering Inside Comprehension

words = ["apple", "tea", "banana"]
long_words = [w for w in words if len(w) > 3]

The final list contains only words longer than three characters. This creates a pipeline inside a single iteration.


Dictionary Comprehension

targets = [2, 4, 6]
double_map = {t: t * 2 for t in targets}

This builds a dictionary with keys and computed values. Comprehensions work across multiple data structures, making iteration expressive.


Iteration in Swift

Swift’s loop features are clean and type-safe.


Iterating Over an Array

let points = [2, 4, 6]

for p in points {
    print(p)
}

Each element is retrieved directly without indexing. Swift’s loop behaves similarly to Python’s for-each pattern.


Enumerating Values and Indexes

for (index, value) in points.enumerated() {
    print(index, value)
}

This provides index and value pairs. It’s helpful when order matters.


Ranges as Iterables

for n in 1...3 {
    print(n)
}

Swift lets you iterate through numeric ranges directly. This is a common pattern for repeated actions.


When to Use Which Pattern

  • Use for…of (JS/TS) or a basic for x in (Python/Swift) when you care about the values.
  • Use for…in only when iterating object keys in JavaScript.
  • Use functional iteration (map, filter, comprehensions) when transforming data.
  • Use enumeration when you also need indexes.
  • Use iterators directly only when you need fine-grained control over iteration.

Choosing the right pattern improves clarity, reduces bugs, and makes your code easier to maintain.


Common Mistakes

Using for…in on arrays (JS)

This returns indexes, not values, which leads to surprising behavior.

Mutating data inside functional loops

Patterns like map should return values rather than update external state.

Forgetting comprehensions create new lists

In Python, comprehensions produce new lists rather than modifying the old one.

Confusing iterator exhaustion

Once an iterator is consumed, you must create a new one if you want to loop again.


Summary

Iteration patterns let you move through data in different ways depending on the structure and your goal. JavaScript uses iterables, iterators, and the distinction between for…of and for…in; Python leans on clean loops and powerful comprehensions; Swift uses type-safe for-each loops and enumerations. Understanding these patterns helps you write clearer, more predictable loops in any language.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster