org.sonar.l10n.javascript.rules.javascript.S1854.html Maven / Gradle / Ivy
Why is this an issue?
Dead stores refer to assignments made to local variables that are subsequently never used or immediately overwritten. Such assignments are
unnecessary and don’t contribute to the functionality or clarity of the code. They may even negatively impact performance. Removing them enhances code
cleanliness and readability. Even if the unnecessary operations do not do any harm in terms of the program’s correctness, they are - at best - a waste
of computing resources.
Exceptions
The 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 compliant
doSomething(rest);
let [x1, x2, x3] = arr; // 'x1' is noncompliant, as omitting syntax can be used: "let [, x2, x3] = arr;"
doSomething(x2, x3);
How to fix it
Remove the unnecesarry assignment, then test the code to make sure that the right-hand side of a given assignment had no side effects (e.g. a
method that writes certain data to a file and returns the number of written bytes).
Code examples
Noncompliant code example
function foo(y) {
let x = 100; // Noncompliant: dead store
x = 150; // Noncompliant: dead store
x = 200;
return x + y;
}
Compliant solution
function foo(y) {
let x = 200; // Compliant: no unnecessary assignment
return x + y;
}
Resources
Standards
Related rules
- {rule:javascript:S1763} - All code should be reachable
- {rule:javascript:S2589} - Boolean expressions should not be gratuitous
- {rule:javascript:S3516} - Function returns should not be invariant
- {rule:javascript:S3626} - Jump statements should not be redundant
© 2015 - 2024 Weber Informatics LLC | Privacy Policy