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?
While I’m familiar with the concept of
assertI wasn’t aware that JavaScript had that functionality. So with that in mind I could be completely wrong but it seems to me that this statement:…is calling a function called
assert(), passing it the parameterfoo.x || valueIfXIsNotDefinedand then comparing the return value from theassert()function withundefined. Perhaps what you need is this:If I try something similar with
console.log():Then it logs:
Similarly, after:
resultis"test".http://jsfiddle.net/YBPyw/
Further, if you actually try to assign
foo.xequal to something (wherefoowas a string) it doesn’t work, so when you later testfoo.xit will giveundefined.