70 lines
1.6 KiB
Plaintext
70 lines
1.6 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
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.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
function foo(a) {
|
|
if (a === 1) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
----
|
|
|
|
|
|
=== Exceptions
|
|
|
|
* Functions returning ``++this++`` are ignored.
|
|
|
|
|
|
[source,javascript]
|
|
----
|
|
function foo() {
|
|
// ...
|
|
return this;
|
|
}
|
|
----
|
|
|
|
* Functions returning expressions having type ``++any++`` are ignored.
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return[MDN - `return`]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Refactor this function to always return the same type.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
Primary: function name/declaration
|
|
|
|
Secondary: Return statements
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|