1

I know that dojo has this feature, but how about jquery or any other libraries?

$.ifObject(foo.bar.baz.qux[0])

if (foo && foo.bar && foo.bar.baz && foo.bar.baz.qux[0])

Assuming arbitrary size of the object nesting, I'm looking for a sugar function that will check whether or not the object I'm looking for is defined, and not crash the server along the way.

Harry
  • 52,711
  • 71
  • 177
  • 261

2 Answers2

1

The simplest way to do this would be to enclose the variable reference in a try-catch block:

try {
  var val = foo.bar.baz.qux[0];
  // succeeded: use val
} catch (ex) {
  // failed: do something else
}
casablanca
  • 69,683
  • 7
  • 133
  • 150
1

In case you want to dive into coffee script, it has a great feature in the ? operator.

if foo?.bar?.baz?.qux?[0]
  alert 'yay!'

Which compiles to this nasty, yet very efficient, javascript

var _ref, _ref2, _ref3;
if (typeof foo !== "undefined" && foo !== null ? (_ref = foo.bar) != null ? (_ref2 = _ref.baz) != null ? (_ref3 = _ref2.qux) != null ? _ref3[0] : void 0 : void 0 : void 0 : void 0) {
  alert('yay!');
}
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337