for-in loop should not be used on arrays

  • Code Quality
  • Low
  • No tags

This rule applies when for-in loop is used on arrays.

for-in loop is not recommended by the following:

  • for-in loop is slower than for loop
  • A variable in for-in loop means index of an array. But programmers tend to consider it as element of an array.

To fix this problem, you can use for loop on arrays. Or, you can use for-of loop in ES6 because for-of loop visits the entries of the array in sequential order and returns the value of the entry.

Noncompliant Code Example

var array = ['foo', 'bar'];

// FORIN_ARRAY alarm
for (var item in array)
    console.log('item: ' + item); // Result: 'item: 0', 'item: 1' (not as expected 'item: foo', 'item: bar')

Compliant Code Example

var array = ['foo', 'bar'];

// When you don't use ES6
for (var i = 0; i < array.length; i++)
    console.log('item: ' + array[i]);

// When you use ES6
for (let item of array)
    console.log(`item: ${item}`);


This rule was introduced in DeepScan 1.0.0-alpha.