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.
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) {
// ...
}
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.
The fix for this issue is straightforward. One just needs to remove the extra boolean cast.
if (!!foo) {
// ...
}
if (foo) {
// ...
}
while (Boolean(foo)) {
// ...
}
while (foo) {
// ...
}