0

Lets say I have a object that among other things contain this.

const forest = {house: {kitchen: {table: {bowl: {fruits: ['apple', 'coconut']}}}}

After function goatsinthehouse() the bowl is gone (along with other things). that would make request like this

exampleFruit = forest.house.kitchen.table.bowl.fruits[0]

it go bananas and throw a "try to get from undefined" and crash unless I have a try/catch Currently I use short circuit to get around this. Like this, but there HAVE to be better way.

exampleFruit = forest || 
               forest.house || 
               forest.house.kitchen || 
               forest.house.kitchen.table.bowl || 
               forest.house.kitchen.table.bowl.fruits || 
               forest.house.kitchen.table.bowl.fruits[0] 
               ? forest.house.kitchen.table.bowl.fruits[0] 
               : 'None';
Griffin
  • 785
  • 5
  • 13
  • Wrap it in a try catch block – John Mar 06 '20 at 11:40
  • if you can support it - [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) is what you're after – Nick Parsons Mar 06 '20 at 11:42
  • Thanks optional chaining is exactly what I was looking for, but unfortunate I think there will be a few years before one can safely assume that it's present... But a question, will not the try/catch solution make something that was syncronus into asyncronus creating the risk of future race conditions? – Griffin Mar 10 '20 at 15:23
  • 1
    try-catch doesn't make something synchronous asynchronous, so that shouldn't be a worry. You could look into using transpilers such as Babel to enable support for newer features if you'd really like to use optional chaining (but it also might use try-catch to make it work). If you're worried about using try-catch, I wrote an optional chaining function in an answer [here](https://stackoverflow.com/questions/58297020/how-to-check-for-availability-for-a-nested-variable-without-checking-all-the-pre/58297408#58297408) which doesn't use try-catch – Nick Parsons Mar 11 '20 at 03:56
  • 1
    @NickParsons that was actually a really clever solution. A cool project would be to somehow tamper with the prototype of Object to inject the functionality if it's not already there :) (not even sure if that is possible) – Griffin Jan 10 '21 at 12:15

0 Answers0