Ignored Result Of A Pure String Method
ID |
javascript.string_result_ignored |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
CWE:252, reliability, suspicious-assignment |
Description
Reports a statement that is nothing but a call to a String method which cannot change anything. Strings are immutable: the method builds a new one and the statement drops it, so the line has no effect at all.
The recognised methods are split in two. Names that only exist on String.prototype — trim, toUpperCase, padStart, split, match and the rest — are reported wherever they appear. Names shared with mutating APIs — replace, replaceAll, slice, concat, normalize — are reported only with evidence that the receiver really is a string: the receiver is a string or template literal, or the call is a replacement whose first argument is a regular expression. Without that, cache.replace(key, value) on some collection type, or node.normalize() on a DOM node, would be reported for doing its job.
javascript.no_unused_expressions cannot cover this: it treats every call as side-effecting, which is the right default when the callee is unknown.
Rationale
// Bad
function normalise(name, path) {
name.trim(); // the untrimmed name is still there
path.replace(/\\/g, "/"); // nothing is replaced
return { name, path };
}
-
Almost always a forgotten assignment, written by someone expecting the in-place semantics of another language’s string type.
-
The value the author wanted is computed and thrown away, and the program carries on with the original text — so the symptom is data that was never cleaned, appearing wherever it is finally used.
-
The statement looks like work being done, which is why it survives review.