61 lines
1.9 KiB
Plaintext

== Why is this an issue?
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 https://developer.mozilla.org/en-US/docs/Glossary/Truthy[_truthy_], and those coerced into ``false`` are said to be https://developer.mozilla.org/en-US/docs/Glossary/Falsy[_falsy_].
Explicit conversion to a boolean can be done with double negation (``!!``) or a ``Boolean`` call. Depending on the context, this may be redundant as JavaScript uses implicit type coercion and automatically converts values to booleans when used with logical operators, conditional statements, or any boolean context.
[source,javascript]
----
if (!!foo) { // Noncompliant: redundant '!!'
// ...
}
if (Boolean(foo)) { // Noncompliant: redundant 'Boolean' call
// ...
}
----
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 condition can be written without the Boolean cast.
[source,javascript]
----
if (foo) {
// ...
}
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion[Boolean coercion]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion[Type coercion]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Truthy[Truthy]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Falsy[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)
=== Message
Disallow unnecessary boolean casts.
'''
== Comments and links
(visible only on this page)
endif::env-github,rspecator-view[]