The result of String.prototype.charAt() should not be compared with a string of length 2 or more

  • BAD_CHAR_AT_COMPARISON
  • Error
  • Medium
  • No tags

This rule applies when the result of String.prototype.charAt() is compared with a string of length 2 or more.

Normally, String.prototype.charAt() returns just a character or an empty string if the index is out of range.

Therefore, when it is compared with a string of length 2 or more, the result will be always false. This is not likely to be a programmer's intent.

Noncompliant Code Example

View with compliant examples side by side
var str = "\nfoo";
if (str.charAt(0) === "/n") { // BAD_CHAR_AT_COMPARISON alarm because "/n" is of length 2.
    console.log("new line at the beginning.");
}

Compliant Code Example

View with noncompliant examples side by side
var str = "\nfoo";
if (str.charAt(0) === "\n") {
    console.log("new line at the beginning.");
}

Version

This rule was introduced in DeepScan 1.5.0-beta.

See

Was this documentation helpful?