80 lines
2.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
The unary operators ``+`` and ``++-++`` can be used to convert some value types to numeric values. But not every value can be converted to a ``++Number++`` type; use it with an object, and result will be ``++NaN++`` (Not A Number). This can be confusing to maintainers.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
var obj = {x : 1};
doSomethingWithNumber(+obj); // Noncompliant
function foo(){
return 1;
}
doSomethingWithNumber(-foo); // Noncompliant
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
var obj = {x : 1};
doSomethingWithNumber(+obj.x);
function foo(){
return 1;
}
doSomethingWithNumber(-foo());
var str = '42';
doSomethingWithNumber(+str);
----
=== Exceptions
2021-04-28 16:49:39 +02:00
Unary ``{plus}`` and ``++-++`` can be used with objects corresponding to primitive types, and ``{plus}`` can be used with ``++Date++``.
[source,javascript]
2021-04-28 16:49:39 +02:00
----
var b = new Boolean(true);
doSomethingWithNumber(-b); // Compliant
var timestamp = +new Date(); // Compliant
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this use of unary {0}.
'''
== Comments And Links
(visible only on this page)
=== on 4 Jun 2015, 12:42:37 Elena Vilchik wrote:
\[~ann.campbell.2] Assign to you for validation and completion (labels, SQALE). CC [~linda.martin]
=== on 4 Jun 2015, 14:21:18 Ann Campbell wrote:
Please double-check my changes [~elena.vilchik]
=== on 4 Jun 2015, 15:36:58 Elena Vilchik wrote:
\[~ann.campbell.2] I added "Exceptions". Check it, please.
=== on 4 Jun 2015, 18:35:32 Ann Campbell wrote:
\[~elena.vilchik] the exceptions look fine, but w/r/t the code samples, we can't just introduce something totally new in the Compliant Solution. The compliant solution shows the Noncompliant example in a "fixed" state. That's why I had added the string example to the Noncompliant solution, marked "compliant".
=== on 16 Jan 2020, 14:18:03 Elena Vilchik wrote:
Deprecated (see details \https://github.com/SonarSource/SonarJS/issues/1810)
endif::env-github,rspecator-view[]