0

My variable a in some scenarios have branch b and in some other - has not. How can I check if a.b.c is defined?

// scenario 1
var a = {
  b: {
    c: "d"
  }
}

// scenario 2
var a = {}

I tried using typeof but without success:

if (typeof a.b.c != 'undefined') {
  console.log('y', a.b.c)
} else {
  console.log('x', a.b.c)
}
curious
  • 671
  • 1
  • 11
  • 25

1 Answers1

0

You can just use if (a.b.c != undefined).

Wai Ha Lee
  • 8,173
  • 68
  • 59
  • 86
ancarofl
  • 58
  • 1
  • 5
  • I'm getting Error `"Cannot read property 'c' of undefined",` – curious May 04 '19 at 20:10
  • Ah, right. ```if (a.b != undefined && a.b.c != undefined)``` should work then. That checks both if a.b is defined and if a.b.c is defined. Up to you whether you need both or only the first part . – ancarofl May 04 '19 at 20:12
  • I got it to work with `((a || {}).b || {}).c;` which is pretty cool (from question from duplicate). – curious May 04 '19 at 20:18