Welcome to MSDN Blogs Sign in | Join | Help

SYSK 223: The Power of Double-Not Operator

If you need to convert a non-boolean data type to a boolean, and you’re dealing with a typeless language (e.g. javascript), you’ve got a couple of choices:  write an if-then-else logic or use the not-not (a.k.a. double-not) operator.  The results are same, so you decide on what style you prefer:

 

[object] => true

false => false

5 => true

a => true

null => false

0 => false

false => false

true => true

-1 => true

 

 

<script type="text/javascript">

    function NotNot(data)

    {           

        if (data)

            document.writeln(data + ' => true <br>');

        else

            document.writeln(data + ' => false <br>');

    }               

          

    NotNot(document);

    NotNot(document == this);

    NotNot(5);     

    NotNot('a');

    NotNot(null);

    NotNot(0);

    NotNot(false);

    NotNot(true);

    NotNot(-1);

   

</script>

 

or

 

<script type="text/javascript">

    function NotNot(data)

    {   

        document.writeln(data + ' => ' + !!data + '<br>');               

    }               

          

    NotNot(document);

    NotNot(document == this);

    NotNot(5);     

    NotNot('a');

    NotNot(null);

    NotNot(0);

    NotNot(false);

    NotNot(true);

    NotNot(-1);

   

</script>



Published Friday, October 20, 2006 5:16 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: SYSK 223: The Power of Double-Not Operator

Friday, October 20, 2006 11:43 AM by James Curran

Isn't you code missing the important part:

   if (!!data)

# SYSK 223: Reply to James Curran

Friday, October 20, 2006 10:58 PM by irenak

There are two examples implementing same logic -- the first is without the !! operator, the second with it.

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker