CodeQL documentation

Unused variable, import, function or class

ID: js/unused-local-variable
Kind: problem
Severity: recommendation
Precision: very-high
Tags:
   - maintainability
Query suites:
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

Unused local variables make code hard to read and understand. Any computation used to initialize an unused variable is wasted, which may lead to performance problems.

Similarly, unused imports and unused functions or classes can be confusing. They may even be a symptom of a bug caused, for example, by an incomplete refactoring.

Recommendation

Remove the unused program element.

Example

In this code, the function f initializes a local variable x with a call to the function expensiveComputation, but later on this variable is never read. Removing x would improve code quality and performance.

function f() {
	var x = expensiveComputation();
	return 23;
}

A slightly subtle case is shown below, where a function expression named f is assigned to a variable f:

var f = function f() {
  return "Hi!";
};
f();

Note that this example involves two distinct variables, both named f: the global variable to which the function is assigned, and the variable implicitly declared by the function expression. The call to f() refers to the former variable, whereas the latter is unused. Hence the example can be rewritten as follows, eliminating the useless variable:

var f = function () {
  return "Hi!";
};
f();

A similar situation can occur with ECMAScript 2015 module exports, as shown in the following example:

export default function f() {
  return "Hi!";
};

Again, the named function expression implicitly declares a variable f, but because the export statement is a default export, this variable is unused and can be eliminated:

export default function () {
  return "Hi!";
};

References