3

I have a method findResult

function findResult(response){
 if (response[0].firstProperty.Value > 0)
     return true;
 else false;
}

In this method, if response object is undefined we get a javascript error. My question is whether to use explicit undefined checks or wrap the code around try/catch as shown below:

function findResult(response){
 try{
    if (response[0].firstProperty.Value > 0)
     return true;
    else return false;
 }
 catch(e){
   return false;
 }

}
4
  • stackoverflow.com/questions/1984721/… Commented Jan 4, 2018 at 8:09
  • there's a myriad of ways to handle this, and not a single one of them has specifically heavy impact compared to the others. (if vs try()catch(){} does not matter) stackoverflow.com/questions/19727905/… The real question here is whether you want to continue executing code in the same block if response is null. if the answer is no, it really does not matter which solution you choose Commented Jan 4, 2018 at 8:11
  • Thanks Timothy. With explict check, the condition check becomes too long Ex: if (response && response.length && response[0].firstProperty.Value > 0) Commented Jan 4, 2018 at 8:57
  • So was checking what is the optimal approach. Thanks for the repsonse Commented Jan 4, 2018 at 8:58

2 Answers 2

0

You can avoid the try catch with a simple check

if (response && response.length && response[0].firstProperty.Value > 0) { ... }

If you have access to lodash:

if (_.get(response, '[0].firstProperty.Value', 0) > 0) { ... }
Sign up to request clarification or add additional context in comments.

Comments

0

Javascript doesn't have this feature native.

But there are some implementations of this on the web. For example:

function deepGet (obj, props, defaultValue) {
    // If we have reached an undefined/null property
    // then stop executing and return the default value.
    // If no default was provided it will be undefined.
    if (obj === undefined || obj === null) {
        return defaultValue;
    }

    // If the path array has no more elements, we've reached
    // the intended property and return its value
    if (props.length === 0) {
        return obj;
    }

    // Prepare our found property and path array for recursion
    var foundSoFar = obj[props[0]];
    var remainingProps = props.slice(1);

    return deepGet(foundSoFar, remainingProps, defaultValue);
}

Usage:

var rels = {
    Viola: {
        Orsino: {
            Olivia: {
                Cesario: null
            }
        }
    }
};
var oliviaRel = deepGet(rels, ["Viola", "Orsino", "Olivia"], {});

Source: http://adripofjavascript.com/blog/drips/making-deep-property-access-safe-in-javascript.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.