3

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?

0

3 Answers 3

3

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; 
Sign up to request clarification or add additional context in comments.

2 Comments

The rules for truthiness for ! and for if are the same.
You are right! I'll amend my answer presently.
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.

Comments

1

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.

6 Comments

I think a six-year-old child understands that the thing after the word "if" is to be interpreted as true or false. !! is just showing off.
@Malvolio: The purpose of the !! is to make the reader aware that the argument isn't a Boolean value, but is being coerced into one.
@supercat -- it would certainly have that effect, but why would the reader care?
@Malvolio: A reader who sees if (woozle(x,y))... and also sees fnord = woozle(x,y);, might expect that fnord would be given a true/false value. Changing the code to if (!!woozle(x,y)) would suggest to the reader that woozle is probably returning something other than a true/false value, and thus avoid creating any false expectations about fnord = woozle(x,y);.
@supercat -- I think your reasoning is sound but your assertions are in error. Far more programmers know how the if statement works than know what !! means. In fact, I would doubt that there are more than a handful of Javascript programmers in the whole world who instinctively assume that the argument to the if statement should be a boolean but have a clue what bang-bang does.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.