-2

If I want to set a constant with a value from a nested object property that can be undefined or set it to a default value, I can do this:

const a = b && b.c && b.c.d ? b.c.d : "default value";

I don't like this syntax because I find it unreadable. I prefer:

const a = b.c.d || "default value";

But this syntax fails if b or c is not an object (undefined). Is there a syntax for this kind of need?

rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • 1
    you could always destructure with the default value in that – Derek Pollard Apr 29 '19 at 20:29
  • There's at least one TC39 proposal: [Optional Chaining for JavaScript](https://github.com/tc39/proposal-optional-chaining) – p.s.w.g Apr 29 '19 at 20:31
  • @DerekPollard Could you please elaborate? (or post your comment as an answer) – rap-2-h Apr 29 '19 at 20:32
  • 1
    For destructuring, you could do `const { c: { d: a = "default value" } = {} } = b || {};`, but personally I find this a lot harder to read. – p.s.w.g Apr 29 '19 at 20:36
  • You could use lodash get method to achieve this. Lodash also provides you a way to set a default value if the value isn't available // _.get(object, path, [defaultValue]) Here is a fiddle that demonstrates the above http://jsfiddle.net/vamshikrishna144/py02dm8L/ – Brr Switch Apr 29 '19 at 20:37

1 Answers1

0

I think this will work,

(b && b.c && b.c.d) || "default value"
Jjagwe Dennis
  • 1,643
  • 9
  • 13
  • You are taking the test and then logically or-ing it with "default value?" I see now, from the questions second example. But I don't think this is what he/she wants. In any case, you should add more description as to why you believe this is the solution – ControlAltDel Apr 29 '19 at 20:34