Unlike strongly typed languages, JavaScript does not enforce a return type on a function. This means that different paths through a function can
return different types of values.
Returning different types from a function can make the code less readable and harder to understand. Maintainers may have to spend more time
figuring out how the function works and what it returns. Additionally, it can be harder to ensure that the code is free of type-related errors.
function foo(a) { // Noncompliant: function returns 'boolean' or 'number'
if (a === 1) {
return true;
}
return 3;
}
Rework the function so that it always returns the same type. This makes the code more consistent and easier to understand. Maintainers can rely on
the function to behave in a predictable way.
function foo(a) {
if (a === 1) {
return true;
}
return false;
}
Exceptions
- Functions returning
this
are ignored.
function foo() {
// ...
return this;
}
- Functions returning expressions having type
any
are ignored.