Unused loop iteration variable¶
ID: js/unused-loop-variableKind: problemSecurity severity: Severity: errorPrecision: highTags: - quality - reliability - correctnessQuery suites: - javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
Mostfor...in andfor...of statements use their iteration variable in the loop body, unless they simply count the number of iterations by incrementing a loop counter in the loop body, or check whether the loop body is executed at all. Loops that do not use their iteration variable but do not fall into one of these two categories may indicate a logic error or typo.
Recommendation¶
Carefully check whether the loop variable should be used. If the variable is genuinely not being used and the code is correct, consider renaming the variable to_ orunused to indicate to readers of the code that it is intentionally unused.
Example¶
In this example, thefor...of loop iteration variablex is never used. It appears that the function is intended to count how many elements of the arrayxs satisfy the filter predicatep, but the programmer forgot to actually passx as an argument top.
functioncountOccurrences(xs,p){varcount=0;for(letxofxs)if(p())++count;returncount;}
To fix this issue, the callp() should be replaced byp(x).