JavaScript

JavaScript

Made by DeepSource

Use for-of loop for array JS-0361

Anti-pattern
Minor

A for-of loop is recommended when the loop index is only used to read from the collection.

Bad Practice

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Recommended

for (const x of arr) {
  console.log(x);
}

for (let i = 0; i < arr.length; i++) {
  // i is used to write to arr, so for-of could not be used.
  arr[i] = 0;
}

for (let i = 0; i < arr.length; i++) {
  // i is used independent of arr, so for-of could not be used.
  console.log(i, arr[i]);
}