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>
Comments
Anonymous
October 20, 2006
Isn't you code missing the important part: if (!!data)Anonymous
October 20, 2006
There are two examples implementing same logic -- the first is without the !! operator, the second with it.