Skip to content

Latest commit

 

History

History
60 lines (46 loc) · 1.31 KB

no-array-for-each.md

File metadata and controls

60 lines (46 loc) · 1.31 KB

Prefer for…of over the forEach method

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Benefits of for…of statement over the forEach method can include:

  • Faster
  • Better readability
  • Ability to exit early with break or return

Fail

array.forEach(element => {
	bar(element);
});
array?.forEach(element => {
	bar(element);
});
array.forEach((element, index) => {
	bar(element, index);
});
array.forEach((element, index, array) => {
	bar(element, index, array);
});

Pass

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