Apr 14, 2009

|| , && and !!

&& is guard operator aka "logical and", and || is default operator "aka logical or", we normally see the code like the following

if ( condtion1 && condition2) { }
if (condition1 || condition2) { }

&& is also know as guard operator. If first operand is truthy, the result is second operand, else result is is first operand. It can be used to avoid null reference.

if (a){
  return a.memeber;
} else {
   return a;
//this is the same
return a && a.member

|| is aslo know is default operator. It is the opposite of && . If first operand is truethy, then result is first operand, else result is second operand. It can be used to fill in default value like the following, it is like ?? in csharp

var last = input || {}; //{} is default value

The !! operator can turn all value into boolean value, you can think of it boolean conversion operator. Keep in mind that truthy/falsy value is not boolean value. For example "hello" is truthy value. So you can write code like

if ("hello")

But "hello" itself is not boolean value, if you want to convert it into boolean value, you need to write

function toBoolean(v)
   if (v)
     return true;
      return false;

var b = "hello";

//or you can just write