Why is this an issue?
If a local variable or a local function is declared but not used, it is dead code and should be removed. Doing so will improve maintainability
because developers will not wonder what the variable or function is used for.
What is the potential impact?
Dead code
An unused variable or local function usually occurs because some logic is no longer required after a code change. In that case, such code becomes
unused and never executed.
Also, if you are writing code for the front-end, every unused variable or function remaining in your codebase is just extra bytes you have to send
over the wire to your users. Unused code bloats your codebase unnecessarily and impacts the performance of your application.
Wrong logic
It could happen that due to a bad copy-paste or autocompletion, the wrong variable is used, while the right one is only declared. In that case, the
unused variable should be used instead of deleted from the codebase.
Memory leaks
Finally, unused functions can also cause memory leaks. For example, an unused function can create a closure over a variable that would otherwise be
released to the garbage collector.
let theThing = null;
const replaceThing = function () {
const originalThing = theThing;
const unused = function () {
if (originalThing) {
console.log("hi");
}
};
theThing = {
longStr: new Array(1000000).join("*"),
someMethod: function () {
console.log(someMessage);
},
};
};
setInterval(replaceThing, 1000);
How to fix it
Usually, the fix for this issue is straightforward, you just need to remove the unused variable declaration, or its name from the declaration
statement if it’s declared along with other variables.
Code examples
Noncompliant code example
function numberOfMinutes(hours) {
var seconds = 0; // seconds is never used
return hours * 60;
}
Compliant solution
function numberOfMinutes(hours) {
return hours * 60;
}
Noncompliant code example
When an array destructuring is used and some element of the array is never referenced, one might simply remove it from the destructuring.
const [_, params] = url.split(path);
Compliant solution
const [, params] = url.split(path);
Resources
Documentation
Articles & blog posts