0

I'm new in node environnement and i want to handle undefined error when i access a children of an undefined object.

Like in this exemple :

console.log(req.body.data.colonne)

if req.body is undefined js throw an error.

If it's a GET method req.body is undefined and req.body.data.colonne so.

i know i can do

if (typeof req.body !== "undefined" and typeof req.body.data !=="undefined" and typeof req.body.colonne !== "undefined")

or successive try block or .hasProperty ...

But can i test if req.body.data.colonne exist even if req.body is undefined without an error ?

Thank !

I found this elegant solution

let column = req.body.data.column || ["*"]

bug00
  • 11
  • 2
  • You shouldn't test the type, but the value. Never use `typeof` to check a propery's value is not `undefined`. This being said, there's no real clean shortcut enabling you to skip intermediate values (other than using a small helper function of course). – Denys Séguret Sep 11 '18 at 09:08
  • Thank a lot, and yeah, it's duplicate question, i'm sorry ! – bug00 Sep 11 '18 at 09:36
  • No worry. Search a little next time and it will be fine ;) – Denys Séguret Sep 11 '18 at 09:41

0 Answers0