0

Looking for a neat way to access a second non-null property from an object when then first property is null or undefined using ES6 object destructuring.

ES5 equivalent:

var obj = { a: null, b: 2 };
var num = obj.a || obj.b; // num = 2

Using ES6 (something like):

const { num: a || b } = obj; // <- how to achieve the above effect here?
  • 5
    There's no such syntax (yet). You can only ```const { a, b } = obj, num = a || b;``` – Artur Jan 03 '18 at 21:53
  • Default syntax in function args and destructuring only applies for `undefined` so if you want default logic for both null and undefined, you need to do it on your own. – loganfsmyth Jan 03 '18 at 23:33

2 Answers2

0
 const { a: num = obj.b } = obj;

(That only works with undefined, not with null)

or

const num = (({a, b}) => a || b)(obj)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    I tried the first, and when I try to access `num` I get a reference error. – Barmar Jan 03 '18 at 21:58
  • @barmar, yup, edited, took it over from OP without thinking about it ... – Jonas Wilms Jan 03 '18 at 22:00
  • Use [Stack Snippet](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) to put the test cases here instead of an external site. – Barmar Jan 03 '18 at 22:06
0

Default values in destructuring work only with undefined, not null. With

var obj = { a: undefined, b: 2}

you could use the horrible hack

var { b: num, a: num = num } = obj;

or its more readable variant

const { b, a: num = b } = obj;

which however introduces an additional identifier b in the scope.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375