github-actions[bot] ee8cb13a08
Create rule S6509: Extra boolean casts should be removed (#1619)
Co-authored-by: Ilia Kebets <104737176+ilia-kebets-sonarsource@users.noreply.github.com>
2023-03-09 15:02:22 +01:00

108 lines
2.6 KiB
Plaintext

In JavaScript, every value can be coerced into a boolean value: either ``true`` or ``false``.
Values that are coerced into ``true`` are said to be _truthy_, and those coerced into ``false`` are said to be _falsy_.
A value's truthiness matters, and depending on the context, it can be necessary or redundant to cast a value to boolean explicitly.
== Why is this an issue?
A boolean cast via double negation (``!!``) or a ``Boolean`` call is redundant when used as a condition, though. The condition can be written without the extra cast and behave exactly the same.
The reason is that JavaScript uses type coercion and automatically converts values to booleans in a specific situation known as a boolean context. The boolean context can be any conditional expression or statement.
For example, these ``if`` statements are equivalent:
[source,javascript]
----
if (!!foo) {
// ...
}
if (Boolean(foo)) {
// ...
}
if (foo) {
// ...
}
----
=== What is the potential impact?
A redundant boolean cast affects code readability. Not only the condition becomes more verbose but it also misleads the reader who might question the intent behind the extra cast.
The more concise the condition, the more readable the code.
== How to fix it
The fix for this issue is straightforward. One just needs to remove the extra boolean cast.
=== Code examples
==== Noncompliant code example
[source,javascript,diff-id=1,diff-type=noncompliant]
----
if (!!foo) {
// ...
}
----
==== Compliant solution
[source,javascript,diff-id=1,diff-type=compliant]
----
if (foo) {
// ...
}
----
==== Noncompliant code example
[source,javascript,diff-id=2,diff-type=noncompliant]
----
while (Boolean(foo)) {
// ...
}
----
==== Compliant solution
[source,javascript,diff-id=2,diff-type=compliant]
----
while (foo) {
// ...
}
----
== Resources
=== Documentation
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion[MDN Boolean coercion]
* https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion[MDN Type coercion]
* https://developer.mozilla.org/en-US/docs/Glossary/Truthy[MDN Truthy]
* https://developer.mozilla.org/en-US/docs/Glossary/Falsy[MDN Falsy]
=== Articles & blog posts
* https://blog.alexdevero.com/truthy-falsy-values-in-javascript/[Alex Devero, How Truthy and Falsy Values in JavaScript Work]
// internal data
ifdef::env-github,rspecator-view[]
'''
== Implementation specification
(visible only on this page)
include::message.adoc[]
'''
== Comments and links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]