Javascript: using "!!" in boolean context

398 Views Asked by At

Is there any reason to use !!someValue (which is equivalent to Boolean(someValue)) in a boolean context? In other words, in situations like if (someValue) ..., does it make sense to write if (!!someValue) ...?

It hurts my eyes and I think it's redundant, but I want to verify that there aren't any edge cases that require it - because I came across a codebase where this seems to be the default way of checking for truthiness.

Clarification: yes, in the general case !!someValue will convert someValue to a boolean; I'm referring to contexts where the runtime will automatically convert someValue to true or false.

3

There are 3 best solutions below

2
ale917k On

That's a helpful way of converting any data type into boolean; The exact synonym would be:

Boolean(someValue)

Some prefer the 'double bang' as being more coincise, while others prefer the classic conversion with Boolean(someValue) for better readability.

So returning to your question, it's most likely redundant in conditions, but it can be handy when needing a conversion from any type to boolean.

0
Nina Scholz On

You never need to use a double bang to convert a boolean value to boolean.

boolean === !!boolean
1
Patrick Barr On

Can't say I know why anyone would rely on directly checking booleans rather than on truthiness, but there is at least one scenario where truthiness is different than coercing with !!.

console.log([] == false); // true
console.log(!![] == false); // false
if([]) { console.log(true); } // true
if([] == false) { console.log(true); } // true
if(!![] == false) { console.log(true); } else { console.log(false); } // false