Google search bar

December 21, 2011

In Javascript, || and && don't evaluate to a boolean

Developers familiar with c-languages may assume that Javascript's || and && operators produce boolean results.  But that isn't necessarily true. What they really do is return one of the two operands.

Truthy-ness (and falsy-ness)
An expression is "truthy" if it isn't "falsy".  The "falsy" values are

  • false (the boolean literal value)
  • "" (the empty string)
  • undefined
  • null
  • NaN (The special number value, representing not a number) 
  • 0 (that's the number, not the string)
The above values are evaluated as false, and all other values are true.

So, false (boolean literal false) is of course, false.  But, perhaps unexpectedly "false" (string literal false), is considered truthy.  

So you can say, "In Javascript 'false' is true".  Absurd but true.

In your code you could right:
if ("false"===true) {
   launchEntireGlobalNuclearArsenal();
}

And because of this interesting absurdity, such a snippet may just destroy the world.

Enough with the truthy-falsy, get on to the operators already!

So, again, <expression1> || <expression2> will return ....

the result of <expression1> if it evaluates to true, else, the result of <expression2>.

So, false || undefined evaluates to ... undefined.
undefined || "Hi!" evaluates to "Hi!"

You can use this to default the value returned from an expression.

someValue || 5.0 ... will evaluate to 5 if someValue is undefined.  But if someValue is boolean false, it will also do that.  As it will with other defined values. so maybe be careful.  You would probably only intend for 5 to be defaulted if someValue===undefined.

Inverse to the behavior of the || operator is that of the && operator.  && returns the first operand (left one) if it is falsy, else it returns the second.

Confused Yet?
If you are...well so was I.  I would refer you to a lecture by Douglas Crockford, it will clarify and teach you some amazing things about javascript.

Finally:
Here is an example I setup on jsfiddle.net.

December 08, 2011

Javascript with operator is bad

In short you don't know if you are changing a property of an object in the with or an implied global variable.  See Crockford's full post.

VirtualBox/USB - Community Ubuntu Documentation

VirtualBox/USB - Community Ubuntu Documentation

I had to add myself to the vboxusers group and then vbox could connect to usb devices. I was able to let other programs access usb without starting the program as root too. So I still need to understand how the group and the bus permissions are linked. But I'm glad to be able to share USB devices with my Virtual Machine.