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);