0

Is there a better / smarter way to do this?

theTitle = responsesToUse[i]["Title"];

if(theTitle == null)
  theTitle = "";
PA.
  • 28,486
  • 9
  • 71
  • 95
Pete Whelan
  • 85
  • 11
  • Does this answer your question? [When should I use ?? (nullish coalescing) vs || (logical OR)?](https://stackoverflow.com/questions/61480993/when-should-i-use-nullish-coalescing-vs-logical-or) – ask4you Nov 16 '22 at 11:41

3 Answers3

3

You can use the nullish coalescing operator. Returns the right side if the left side is null or undefined:

const theTitle = responsesToUse[i]["Title"] ?? "Default value";

Additionally you can use the logical or operator. It will check if left value is falsy and return the right side:

const theTitle = responsesToUse[i]["Title"] || "Default value";

This question is answered here

ask4you
  • 768
  • 3
  • 14
  • the _falsy_ check is misleading in this case, because it can misinterpret valid `0` or `""` values. – PA. Nov 17 '22 at 11:23
-1
theTitle = responsesToUse[i]["Title"] ?? "";
Zeephyros
  • 11
  • 5
-1

Logical OR operator can be used:

const theTitle = responsesToUse?.[i]?.["Title"] || "";

use ?. to check if the required index/ property exist in the source, else fallback to right side value.

Hope that helps.

Manish Kumar
  • 1,131
  • 15
  • 28
  • probably the downvoter thought that the falsy check is misleading in this case, because it can misinterpret valid 0 or "" values. – PA. Nov 17 '22 at 11:26