prefer-for-of-loops-over-array-methods
Installation
SKILL.md
Summary
Prefer native for (const item of items) loops over Array methods like forEach. While map and filter are acceptable for simple transformations, forEach should never be used.
Rationale
- Debugging:
forEachcallbacks create new stack frames, making "Step Over" debugging difficult (it steps into the callback or finishes the loop entirely).for-ofkeeps execution in the current scope. - Performance:
for-ofis generally faster as it avoids the function call overhead for every element. - Control Flow:
forEachdoes not supportawait,break, orcontinuein a standard way.for-ofhandles these naturally.
Guidance
- Strict Ban: Do not use
Array.prototype.forEach. Always replace it withfor-of. - Preference: Use
for-offor any logic involving side effects, asynchronousawait, or complex bodies. - Exceptions:
- One-Liners: Simple
mapandfilterchains are allowed for pure data transformations (e.g.,const names = users.map(u => u.name)). - If the transformation becomes complex or multi-line, prefer
for-ofwith an explicit accumulator.
- One-Liners: Simple