Bipolar: Objects vs. Primatives

Boolean(0) === false
new Boolean(0) == false
new Boolean(0).valueOf() === false
!new Boolean(0) == false
Number(0) === 0
new Number(0) == 0
new Number(0).valueOf() === 0
!new Number(0) == 0

After my initial startle, I remembered that objects are always truish in JavaScript. So an object that has a meaning of false is still truish. Below is the same set of statements with comments:

// cast as boolean
Boolean(0) === false
// a new object with value of false
new Boolean(0) !== false
new Boolean(0) == false
!new Boolean(0) == false
// get the primative value of the object
new Boolean(0).valueOf() === false
// cast as number
Number(0) === 0
// a new number with a value of 0
new Number(0) !== 0
new Number(0) == 0
!new Number(0) == 0
// get the primative value of the object
new Number(0).valueOf() === 0

So I ended up with the following functions:

function isFalsy(o) {
  return (o && o.valueOf ? !o.valueOf() : !o);
}

function isTruish(o) {
  return (o && o.valueOf ? !!o.valueOf() : !!o);
}

Still, it is fun to say that there is a situation where “something == false” and “!something == false”.