Skip to content

Latest commit

 

History

History
30 lines (20 loc) · 835 Bytes

no-for-loop.md

File metadata and controls

30 lines (20 loc) · 835 Bytes

Do not use a for loop that can be replaced with a for-of loop

There's no reason to use old school for loops anymore for the common case. You can instead use for-of loop (with .entries() if you need to access the index).

Off-by-one errors are one of the most common bugs in software. Swift actually removed this completely from the language..

This rule is fixable unless index or element variables were used outside of the loop.

Fail

for (let index = 0; index < array.length; index++) {
	const element = array[index];
	console.log(index, element);
}

Pass

for (const [index, element] of array.entries()) {
	console.log(index, element);
}

for (const element of array) {
	console.log(element);
}