ocodo
ocodo

Reputation: 30248

Check if a nested property is defined in CoffeeScript?

Checking if simple variables are defined is made easy with myVar?

The question is, is there a nice way in CoffeeScript to check if a nested property is defined?

e.g.

if property.p.p.p.p?
  alert "Hello"

Throws a ReferenceError if property.p.p.p (or property.p.p | property.p) aren't defined.

Is this just something we have to recursively check, or is there a nice feature?

Upvotes: 3

Views: 962

Answers (1)

Ben McCormick
Ben McCormick

Reputation: 25718

if property?.p?.p?.p?.p?
  alert "Hello"

Does what you want.

that translates to

var _ref, _ref1, _ref2;

if ((typeof property !== "undefined" && property !== null ? (_ref = property.p) != null ? (_ref1 = _ref.p) != null ? (_ref2 = _ref1.p) != null ? _ref2.p : void 0 : void 0 : void 0 : void 0) != null) {
  alert("Hello");
}

in JS.

The relevant piece of the docs:

The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined. If all of the properties exist then you'll get the expected result, if the chain is broken, undefined is returned instead of the TypeError that would be raised otherwise.

Upvotes: 13

Related Questions