58 lines
1.8 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
In JavaScript, a setter is a special type of function that is used to set the value of a property on an object. Setters are defined using the ``++set++`` keyword followed by the name of the property that the setter is associated with.
2021-04-28 16:49:39 +02:00
To set the property, we simply assign a value to it as if it were a regular property. The setter function is automatically called with the value that we assign to the property.
Functions declared with the ``++set++`` keyword will automatically return the values they were passed. Thus any value explicitly returned from a setter will be ignored, and explicitly returning a value is a mistake.
2021-04-28 16:49:39 +02:00
[source,javascript,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
let person = {
2021-04-28 16:49:39 +02:00
// ...
set firstname(first) {
this.first = first;
return 42; // Noncompliant: The return value 42 will be ignored
2021-04-28 16:49:39 +02:00
}
};
console.log(person.firstname = 'bob'); // Prints 'bob'
2021-04-28 16:49:39 +02:00
----
Since return values in setters are ignored, you should remove return statements altogether.
[source,javascript,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
let person = {
2021-04-28 16:49:39 +02:00
// ...
set firstname(first) {
this.first = first;
2021-04-28 16:49:39 +02:00
}
};
console.log(person.firstname = 'bob'); // Prints 'bob'
2021-04-28 16:49:39 +02:00
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set[set]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Consider removing this return statement; it will be ignored.
'''
== Comments And Links
(visible only on this page)
=== on 21 Apr 2017, 14:41:26 Elena Vilchik wrote:
\[~jeanchristophe.collet] Could you please update message of this rule so that it is a bit softer and gives some details of the problem? (issue \https://github.com/SonarSource/sonar-javascript/issues/572)
endif::env-github,rspecator-view[]