0

I currently have this JavaScript function lying around within my code:

getCoverPhoto(item) {
  if (item != undefined && item.gallery != undefined && item.gallery[0] != undefined)
    return item.gallery[0].media;
  return "";
}

How can I simplify the if condition above? And if it can't be simplified, can it be written in a better way?

Mahatmasamatman
  • 1,537
  • 2
  • 6
  • 20
Ziad Akiki
  • 2,601
  • 2
  • 26
  • 41
  • 1
    your solution does not check for null, that said, I'd check for "trueish" instead. As time of writing, only typescript supports 'a real better way": https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html `return item?.gallery?.[0]?.media ?? '';` – Christoph Lütjen Mar 08 '20 at 17:08
  • Does this answer your question? [Test for existence of nested JavaScript object key](https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key) – ASDFGerte Mar 08 '20 at 17:15
  • 1
    @ChristophLütjen optional chaining and null coalescing works e.g. in chrome and node already (both same engine afterall). Obviously still doesnt work everywhere, e.g. not in FF. Both are part of the ES2020 spec. – ASDFGerte Mar 08 '20 at 17:19
  • @ASDFGerte thx, wasn't aware of this - both operators seem to work in Chrome, Edge, Firefox (but not in e.g. Safari) – Christoph Lütjen Mar 08 '20 at 17:29

3 Answers3

1

For example with ternary operator:

getCoverPhoto(item) {
  return item && item.gallery && item.gallery[0] ? item.gallery[0].media : '';
}

Read further in the documentation:

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.

Or with ES6+:

const getCoverPhoto = item => item && item.gallery && item.gallery[0] ? item.gallery[0].media : '';

I hope that helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
0

Here is a more simplified version of your code.

getCoverPhoto(item) {
  if (item && item.gallery && item.gallery[0])
    return item.gallery[0].media;
  return "";
}
Anurodh Singh
  • 814
  • 5
  • 9
0

Use destructing to reduce the conditions. Below code should work for you.

getCoverPhoto(item) { 

      const { gallery = [] }= item; // this is destructing with default value assignment.
      return item.gallery[0] ? item.gallery[0].media : '';
    }
Shumi Gupta
  • 1,505
  • 2
  • 19
  • 28