0

Let's define an object.

const obj = {};

We can check that obj.x is undefined since we can control it like that:

if(typeof obj.x === "undefined") console.log("error");

However, how can I also check if obj.x.y is undefined withouth try, catch block.

if(typeof obj.x.y === "undefined") console.log("error"); // Throws and error

I'm doing and application which gets response from a server and I need check object like error.response.data.error.message is undefined or not.

Mehmet Ali
  • 313
  • 3
  • 15
  • `typeof obj.x === "undefined" && typeof obj.x.y === "undefined"`. Although it's much shorter as `obj.x && obj.x.y` – VLAZ Nov 19 '20 at 10:00
  • 1
    Or you can use optional chaining like `ìf(obj?.x?.y)` – Eldar Nov 19 '20 at 10:03
  • 2
    Like this `if(obj?.x?.y)`. This is called Optional Chaining. You can read about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) – Aditya Menon Nov 19 '20 at 10:05

0 Answers0