Skip to content Skip to sidebar Skip to footer

Why Is The !! Preferable In Checking If An Object Is True?

Some JavaScript examples use !! to check if an object is available // Check to see if Web Workers are supported if (!!window.Worker) { // Yes, I can delegate the boring stuff! }

Solution 1:

It isn't preferable, or even different, in this case. The double-bang converts the variable that follows it into a Boolean value (similar to wrapping in the Boolean() constructor). Gets around potential problems with truthy and falsey variables.

However, putting the variable alone in an if() clause does the same thing (it also resolves the contents of the if's parens to a hard Boolean).

The double-bang can prove helpful in other cases, such as if you want to return a true or false at the end of a function based on a variable's truthiness/falsiness. That would be rather than:

if(condition) {
  returntrue;
} else {
  returnfalse;
}

You could simply write:

return !!condition; 

Solution 2:

It isn't.

!! is useful when you are passing an object into a function that (like jQuery's toggle()) checks to see if its argument is a boolean, or when the function might stash its argument and thereby prevent the object from being collected.

The case you cite is neither of those. Use a bare if.

Solution 3:

In the condition of an if statement both versions will do the same thing and its a stylistic choice. Some people prefer use !! to highlight that Worker is not a boolean and is being converted tto boolean.

Post a Comment for "Why Is The !! Preferable In Checking If An Object Is True?"