0

    // option 1
    let val = a.b.c.d || null; 
    // this gives error if a.b.c is undefined or a.b is undefined etc.

    // option 2: alternate version
    let val2 = null;
    if (a.b && a.b.c && a.b.c.d) {
        val2 = a.b.c.d;
    }

Is there an elegant way of writing the above code that is somewhat similar to option 1?

  • You can use `try{...} catch(ex){ default assumptions}` – Rajesh Nov 24 '17 at 11:47
  • Unfortunately there's no efficient and elegant way for that in Javascript right now, other than avoiding being in this situation. You often end up with some helpers ([example](https://github.com/Canop/miaou/blob/master/libs/Miaou.js#L27)). – Denys Séguret Nov 24 '17 at 11:48
  • my life gets easier if a.b.c.d returned undefined if a.b.c was undefined; but no! – Ashwini Kumar Nov 24 '17 at 11:48
  • 1
    Please search thoroughly before posting. More on searching [here](/help/searching). – T.J. Crowder Nov 24 '17 at 11:50
  • Thanks TJ, I will learn more about search and its importance to the "world wide web". Was curious, is searching a problem or reading long verbose questions and answers an issue? – Ashwini Kumar Nov 28 '17 at 08:59

0 Answers0