for-in
loop should not be used on arrays
- FORIN_ARRAY
- Code Quality
- Low
- No tags
This rule applies when for-in
loop is used on arrays.
for-in
loop is not recommended on arrays for the following reasons:
for-in
loop is slower thanfor
loop.for-in
loop variable holds array indexes. But programmers tend to consider it as having array elements.
For better performance, it is recommended to use for
loops on arrays. Or if performance is not critical and the array indexes are not needed, you can consider using for-of
loop whose loop variable holds the array elements.
Noncompliant Code Example
View with compliant examples side by sideconst array = ['foo', 'bar'];
// FORIN_ARRAY alarm
for (const item in array) {
console.log('item: ' + item); // Result: 'item: 0', 'item: 1' (not as expected 'item: foo', 'item: bar')
}
Compliant Code Example
View with noncompliant examples side by sideconst array = ['foo', 'bar'];
for (const item of array) {
console.log(`item: ${item}`);
}
Version
This rule was introduced in DeepScan 1.0.0-alpha.