0

I'm tired of null validations to prevent undefined errors, like:

function do(){
    if(!!object && !!object.childObject && !!object.childObject.prop)
        doSomethingWithProp(object.childObject.prop);
}

Why?

If the validation was only if(!!object.childObject.prop) I could get undefined error with childObject or object.

Lucas
  • 1,251
  • 4
  • 16
  • 34
  • wow.... in suggested questions this topic didn't appear – Lucas Jul 14 '16 at 18:47
  • You can also use underscore or lodash, i.e. _.has(myObject, "some.Nested.Propert.Path.In.MyObject") will return true/false, or you can use _.get(myObject, "some.Nested.Propert.Path.In.MyObject", fallbackValueHere) to get that nested property if it exists, and if it doesn't, then fallbackValueHere will be returned instead. That's essentially what the accepted answer from the link posted above is doing, but in a more performant and easier to use manner. – matmo Jul 14 '16 at 18:49
  • You don't need the `!!`. – gcampbell Jul 14 '16 at 18:55
  • It is for semantics. Without `!!` looks like `boolean` – Lucas Jul 15 '16 at 19:23

0 Answers0