JS: Preventing error while accessing attributes of an Undefined object

My goal: to check if the object attribute matches / true. However, in some cases, the object is undefined.


It's not a problem. The script continues normally.

if(somethingUndefined){ }


However, if I try to access the attribute of an undefined object, this will result in an error and stop the script.

if(somethingUndefined.anAttribute){ }


Right now, this is what I'm using to solve the problem:

if(somethingUndefined && somethingUndefined.anAttribute){ }


Is there any other way to do this? Perhaps global parameters that return false if the program tries to access the attribute of an undefined object?

+4
source share
3 answers

If you have many if statements, such as if(somethingUndefined && somethingUndefined.anAttribute){ } , then you can assign it an empty object when it is undefined.

 var somethingUndefined = somethingUndefined || {}; if (somethingUndefined.anAttribute) { } 
+1
source

You can use the JavaScript feature to assign variables in if conditions and follow this pattern for faster verification after you pass the first nested object.

Jsperf

 var x; if( (x = somethingUndefined) && // somethingUndefined exists? (x = x.anAttribute) && // x and anAttribute exists? (x = x.subAttrubute) // x and subAttrubute exists? ){ } 

versus traditional

 if( somethingUndefined && // somethingUndefined exists? somethingUndefined.anAttribute && // somethingUndefined and anAttribute exists? somethingUndefined.anAttribute.subAttribute // somethingUndefined and anAttribute and subAttribute exists? ){ } 
+1
source

The way you do this in your question, usually the way it is done in javascript. If you find yourself using this a lot, you can abstract it into a function to make things a little clean for yourself, as such:

 if (attrDefined(obj, 'property')) { console.log('it is defined, whoo!'); } function attrDefined(o, p){ return !!(o && o[p]) } 
0
source

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


All Articles