I've often used the following pattern in my Javascript:
x = couldBeNullThing || valueIfItIsNull;
because it beats than:
x = couldBeNullThing ? couldBeNullThing : valueIfItIsNull;
I also frequently use a slight variant of that same pattern:
x = x || valueIfXIsNotDefined;
That's all great ... except the problem is, I recently discovered:
foo = "";
//assert foo.x === undefined;
foo.x = foo.x || valueIfXIsNotDefined;
//assert foo.x === undefined;
In other words, if you have a string, and you do string.aPropertyThatStringDoesntHave || foo, you'll get back neither foo nor an actual value; instead you get undefined.
Can anyone explain why this is? It seems to me that if foo.x is undefined, then foo.x || anythingElse should always result in anythingElse ... so why doesn't it?