CodeQL queries 1.25
Skip to end of metadata
Go to start of metadata

Name: Return statement assigns local variable

Description: An assignment to a local variable in a return statement is useless, since the variable will immediately go out of scope and its value is lost.

ID: js/useless-assignment-in-return

Kind: problem

Severity: warning

Precision: very-high

Query: ReturnAssignsLocal.ql
/**
 * @name Return statement assigns local variable
 * @description An assignment to a local variable in a return statement is useless, since the variable will
 *              immediately go out of scope and its value is lost.
 * @kind problem
 * @problem.severity warning
 * @id js/useless-assignment-in-return
 * @tags maintainability
 *       readability
 *       external/cwe/cwe-563
 * @precision very-high
 */

import javascript
import semmle.javascript.RestrictedLocations

from ReturnStmt r, AssignExpr assgn, Variable v
where
  assgn = r.getExpr().stripParens() and
  v = r.getContainer().(Function).getScope().getAVariable() and
  not v.isCaptured() and
  assgn.getLhs() = v.getAnAccess()
select r.(FirstLineOf),
  "The assignment to " + v.getName() +
    " is useless, since it is a local variable and will go out of scope."

Assigning a local variable in a return statement is useless, since the local variable will go out of scope immediately and its new value is lost.

Recommendation

Closely examine the code in question to understand the original intention. For instance, the assignment may originally have referred to a variable from another scope that accidentally was shadowed due to a renaming; in this case, perform another renaming to make it visible again. Or maybe the assignment was meant to assign to a property of the receiver object and the programmer inadvertently forgot to qualify it by this; address this by providing the required qualification. Finally, the assignment may simply be unnecessary, in which case it can be removed.

Example

In the following example, the getName method of Person contains a useless assignment to name.

function Person(first, last, age) {
	this.first = first;
	this.last = last;
	this.age = age;
}

Person.prototype.getName = function() {
	var name = first + " " + last;
	return name = name.trim();
};

The assignment serves no obvious purpose and should be removed:

function Person(first, last, age) {
	this.first = first;
	this.last = last;
	this.age = age;
}

Person.prototype.getName = function() {
	var name = first + " " + last;
	return name.trim();
};

References