Unused index variable¶
ID: js/unused-index-variableKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - correctnessQuery suites: - javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
If the loop variable of afor loop ranges over the indices of an array, that variable would normally be used as an array index in the body of the loop. If, instead, the loop body only refers to array elements at constant indices, this may indicate a logic error or leftover testing code.
Recommendation¶
Examine the loop carefully to ensure it is behaving as expected. You may want to consider using afor-of loop to iterate over all elements of an array without the need for error-prone index manipulations.
Example¶
The following example shows a function that is intended to sum up the elements of an arrayxs. The loop variablei is counted up from zero toxs.length-1, but instead of addingxs[i] to the running sumres, the code addsxs[0], the first element ofxs, to it, which is likely a mistake:
functionsum(xs){varres=0;for(vari=0;i<xs.length;++i)res+=xs[0];// BAD: should be xs[i]returnres;}
The problem can be fixed by addingxs[i] instead:
functionsum(xs){varres=0;for(vari=0;i<xs.length;++i)res+=xs[i];returnres;}
Alternatively, the function can be written more succinctly using afor-of loop:
functionsum(xs){varres=0;for(varxofxs)res+=x;returnres;}