1

What's an easy way to check

if (a.b.v.c.d.e === true) {}

and return false if any of b or c or v is undefined?

Coffeescript handles it easily but what is a comparable solution in vanilla javascript? Is there a library that has this common issue taken cared of?

Harry
  • 52,711
  • 71
  • 177
  • 261

3 Answers3

1

Javascript does not have a pretty feature to do this (without using any helper functions). You can use && operator to do this:

if (a && a.b && a.b.v && a.b.v.c && a.b.v.c.d && a.b.v.c.d.e === true) {}
madox2
  • 49,493
  • 17
  • 99
  • 99
1

You can use the short-circuiting behavior of && to express the chained dependencies.

if (a && a.b && a.b.v && a.b.v.c && a.b.v.c.d && a.b.v.c.d.e === true)
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Write a function and call it like this:

if (ignoreNulls(a, 'b', 'v', 'c', 'd', 'e') == true) {
  // ...
}


function ignoreNulls() {
  var args = Array.prototype.slice.call(arguments);
  var subj = args.shift();
  while (prop = args.shift()) {
    var v = subj[prop];
    if (v !== null && v != undefined) {
      subj = v
    } else {
      return null;
    }
  }
  return subj;
}
Leventix
  • 3,789
  • 1
  • 32
  • 41