CodeQL documentation

Missing ‘.length’ in comparison

ID: js/missing-dot-length-in-comparison
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - quality
   - reliability
   - correctness
Query suites:
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

It is very common to check whether a number is within the bounds of an array or string using a comparison of form i < array.length, and later perform an indexing access array[i]. If this comparison is mistyped as i < array, a type coercion will be performed, which almost never has the intended effect.

Recommendation

Check if one of the operands is an array or a string, and make sure to compare against its length, not against the value itself.

Example

The following example shows a mistyped loop condition i < array:

for (var i = 0; i < array; ++i) {
    count += array[i]
}

If the above is executed with array set to [3,5,7], the loop will not run at all. The error can be corrected by changing the loop condition to i < array.length:

for (var i = 0; i < array.length; ++i) {
    count += array[i]
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy