0

I saw this line of code in a book:

!!(document.all && document.uniqueID);

Why is it necessary to use the double not operator? Do not the && operator already transform the result to a Boolean?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tt0686
  • 1,771
  • 6
  • 31
  • 60
  • 2
    IMO !! is unnecessary here – webduvet Apr 01 '14 at 11:33
  • No, the && operator doesn't change the result to a boolean, and yes, it may be necessary, depending on whether you need or not a boolean. – Denys Séguret Apr 01 '14 at 11:35
  • 2
    @lombausch Why do you say that ? If the author wants a boolean, this may be necessary. – Denys Séguret Apr 01 '14 at 11:35
  • " *However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value* " : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators – Alex K. Apr 01 '14 at 11:36
  • @AlexK. :) I had no idea it works like this. thanks for pointing out. – webduvet Apr 01 '14 at 11:38

1 Answers1

2

&& will return the value of document.uniqueID (if document.all has any value other than '',false, null, undefined, 0, NaN) for document.all && document.uniqueID:

 for Example 45 === (true && 45) //true

From mozilla.org.

Logical AND (&&) expr1 && expr2 returns expr1 if it can be converted to false; otherwise, it returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, it returns false.

So it is necessary to use !! to convert the above expression into Boolean.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anoop
  • 23,044
  • 10
  • 62
  • 76