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:

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

if (!!foo) {
    // ...
}

Compliant solution

if (foo) {
    // ...
}

Noncompliant code example

while (Boolean(foo)) {
    // ...
}

Compliant solution

while (foo) {
    // ...
}

Resources

Documentation

Articles & blog posts