Javascript Undefined String Property Truthiness

I often used the following template in my Javascript:

x = couldBeNullThing || valueIfItIsNull; 

because it surpasses:

 x = couldBeNullThing ? couldBeNullThing : valueIfItIsNull; 

I also often use a small version of the same template:

 x = x || valueIfXIsNotDefined; 

That everything is great ... except for the problem, 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 will not get either foo nor the actual value; instead, you will get undefined.

Can someone explain why this is? It seems to me that if foo.x is undefined, then foo.x || anythingElse should always lead to something Else ... so why is it not?

+4
source share
1 answer

While I was familiar with the concept of assert , I did not know that JavaScript had this functionality. Therefore, bearing in mind, I could be completely wrong, but it seems to me that this statement:

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

... calls a function called assert() , passing it the parameter foo.x || valueIfXIsNotDefined foo.x || valueIfXIsNotDefined , and then comparing the return value with the assert() function with undefined . Perhaps you need the following:

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

If I try something like this 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 "test" .

http://jsfiddle.net/YBPyw/

Also, if you are really trying to set foo.x to something (where foo was a string), this will not work, so when you check foo.x later, it will give undefined .

+2
source

Source: https://habr.com/ru/post/1403185/


All Articles