Why is the !! preferable in checking if an object is true? [duplicate]

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!

Why is this preferred to just if (window,Worker) and in what context would this fail?



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) {
  return true;
} else {
  return false;

You could simply write:

return !!condition; 

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.


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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.