-1

what is the best aproach to check if a "deep" structure is undefined?

For example I have some check like this:

if (json.error.message != undefined) {
    console.log(json.error.message);
}

The problem here is, that if json.error is already undefined this will crash. So I would need to write something like:

if (json.error != undefined && json.error.message != undefined) {
    console.log(json.error.message);
}

But this could not be the best aproach or? When I would have even "deeper" structures.

gurehbgui
  • 14,236
  • 32
  • 106
  • 178
  • 1
    [Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?](https://stackoverflow.com/q/6613952/102937) – Robert Harvey Jan 14 '21 at 19:56
  • Check this article about `Elvis` operator aka safe navigation operator.https://www.beyondjava.net/elvis-operator-aka-safe-navigation-javascript-typescript – Mu-Majid Jan 14 '21 at 20:02

1 Answers1

1
if (json?.error?.message != undefined) {
    console.log(json.error.message);
}
novarx
  • 498
  • 3
  • 6