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;
 }

}
Sandeep Nagaraj
  • 118
  • 1
  • 11
  • https://stackoverflow.com/questions/1984721/how-to-handle-undefined-in-javascript – atilkan Jan 04 '18 at 08: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) https://stackoverflow.com/questions/19727905/in-javascript-is-it-expensive-to-use-try-catch-blocks-even-if-an-exception-is-n 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 – Timothy Groote Jan 04 '18 at 08:11
  • Thanks Timothy. With explict check, the condition check becomes too long Ex: if (response && response.length && response[0].firstProperty.Value > 0) – Sandeep Nagaraj Jan 04 '18 at 08:57
  • So was checking what is the optimal approach. Thanks for the repsonse – Sandeep Nagaraj Jan 04 '18 at 08:58

2 Answers2

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) { ... }
klugjo
  • 19,422
  • 8
  • 57
  • 75
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

Renan Araújo
  • 3,533
  • 11
  • 39
  • 49