Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Undefined String Property Truthiness

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?

like image 910
machineghost Avatar asked Nov 04 '22 03:11

machineghost


1 Answers

While I'm familiar with the concept of assert I 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:

assert (foo.x || valueIfXIsNotDefined) === undefined;

...is calling a function called assert(), passing it the parameter foo.x || valueIfXIsNotDefined and then comparing the return value from the assert() function with undefined. Perhaps what you need is this:

assert(foo.x || valueIfXIsNotDefined === undefined);

If I try something similar with console.log():

var foo = "",
    valueIfXIsNotDefined = "test";
console.log( foo.x === undefined);
console.log(foo.x || valueIfXIsNotDefined === undefined);

​Then it logs:

true
false

Similarly, after:

var result = foo.x || valueIfXIsNotDefined;

result is "test".

http://jsfiddle.net/YBPyw/

Further, if you actually try to assign foo.x equal to something (where foo was a string) it doesn't work, so when you later test foo.x it will give undefined.

like image 162
nnnnnn Avatar answered Nov 09 '22 12:11

nnnnnn