Why you should care
For the same number of loop iterations, a forin loop can end up as much as seven times slower than the other loop types. For this reason, it’s recommended to avoid the for-in loop unless your intent is to iterate over an unknown number of object properties.
Moreover when using with arrays, This is however very error prone because it does not loop from 0
to length - 1
but over all the present keys in the object and its prototype chain. Here are a few cases where it fails:
function printArray(arr) {
for (var key in arr) {
print(arr[key]);
}
}
printArray([0,1,2,3]); // This works.
var a = new Array(10);
printArray(a); // This is wrong.
a = doc.getElementsByTagName(‘*’); printArray(a); // This is wrong.
a = [0,1,2,3]; a.buhu = ‘wine’; printArray(a); // This is wrong again.
a = new Array; a[3] = 3;
printArray(a); // This is wrong again
CAST Recommendations
References
How we detect
bad:
function printArray(arr) {
for (var key in arr) {
print(arr[key]);
}
}
good :
function printArray(arr) {
var l = arr.length;
for (var i = 0; i < l; i++) {
print(arr[i]);
}
}
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.