A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value
only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it’s not an error, it is at best a waste of resources.
Therefore all calculated values should be used.
Noncompliant Code Example
i = a + b; // Noncompliant; calculation result not used before value is overwritten
i = compute();
Compliant Solution
i = a + b;
i += compute();
Exceptions
- This rule ignores initializations to -1, 0, 1,
undefined
, [], {}, true
, false
and ""
.
- Variables that start with an underscore (e.g. '
_unused
') are ignored.
- Assignment of
null
is ignored because it is sometimes used to help garbage collection
- Increment and decrement expressions are ignored because they are often used idiomatically instead of
x+1
- This rule also ignores variables declared with object destructuring using rest syntax (used to exclude some properties from object):
let {a, b, ...rest} = obj; // 'a' and 'b' are ok
doSomething(rest);
let [x1, x2, x3] = arr; // but 'x1' is noncompliant, as omitting syntax can be used: "let [, x2, x3] = arr;"
doSomething(x2, x3);
See
- MITRE, CWE-563 - Assignment to Variable without Use ('Unused Variable')