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

  • BAD_CHAR_AT_COMPARISON
  • Error
  • Medium
  • No tags

This rule applies when String.prototype.charAt() result 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

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

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