Is there any ways to short-up such chain call?
if (obj && obj.prop && obj.prop.subProp1 && obj.prop.subProp1.subPropFunc) {
obj.prop.subProp1.subPropFunc();
}
The only alternative I can imagine is try-catch. Any other ideas?
*I really tired of writing these. It’s much easier in coffeescript using ?..
This should work given your sample code (haven’t tested “all cases”, just a copy of your sample):
The method
propsExist()takes a variable number of arguments, the first of which being the original object you want to check properties/functions on. It will iterate through the list of properties you send to it and check them in-order. If one doesn’t exist, it will returnfalse. If it makes it through the whole loop, it validated successfully!If you always want to call the sub-property’s function if it validates, you could also just change the
propsExistfunction to call it instead of returning true (then rename the function to something likecallIfValid(obj, ...)