Yury Tarabanko Yury Tarabanko -3 years ago 165
CoffeeScript Question

Destructuring assignment and null coalescing

For a singular assignment in CoffeeScript, you can use the existential operator:

name = obj?.props?.name

This results in a rather lengthy block of code, that checks that
are defined.

name = typeof obj !== "undefined" && obj !== null ?
(_ref2 = obj.props) != null ?
_ref2.name : void 0 : void 0;

Consider a more complex, destructuring assignment:

{name: name, emails: [primary], age: age} = Person.get(id)

If the object contains no
property, that code would throw a
. Is there any way to use the existential operator with these kinds of destructuring assignments?

This is the best alternative I have so far:

{name: name, emails: emails, age: age} = Person.get(id)
primary = emails?[0]

Answer Source

In ES6, you can do this:

const {name: name, emails: [primary] = [], age: age} = Person.get(id)

If Person.get(id) returns an empty object, primary will be undefined (no TypeError is thrown).

The forthcoming CoffeeScript 2 supports this as well, which you can try at http://coffeescript.org/v2/#try

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download