I have some objects with properties. I wanted to test to see if they had characters in them so I initially wrote this:
if (MyObject.Prop1.length > 0) {....}
However, sometimes the object may not have a certain property so I was getting the error "cannot get length".
I changed it by writing this:
if (MyObject.Prop1 && MyObject.Prop1.length > 0) {....}
I'm using the chrome inspector and when I run the code, I don't get the error anymore. Is this going to work in every browser?
Thanks.
As an alternative:
if ('Prop1' in MyObject && MyObject.Prop1.length > 0) { ... )
Or, to be even more careful:
if (MyObject.hasOwnProperty('Prop1') && MyObject.Prop1.length > 0) { ... }
Of course that might be the wrong thing to do, depending on the nature of "MyObject".
Yes it will work quite fine, although you can save yourself the > 0 and just do
if (MyObject.Prop1 && MyObject.Prop1.length) {....}
since anything other than zero will evaluate to true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With