0

I have a long chain of objects and want to check if the last object in the chain is null. Like this:

if(obj1.obj2.obj3.obj4) {
    // obj4 is not null --> do stuff
}

However if obj3 is null, I get an exception. So I would have to do:

if(obj1.obj2.obj3) {
    // obj3 is not null
    if(obj1.obj2.obj3.obj4) {
        // obj4 is not null --> do stuff
    }
}

obj1 and obj2 might be also null, so I have to check these as well. I'm sure there must be a better way to implement this, instead of doing if-chains.

Beric
  • 63
  • 2
  • 9
  • You don't have to do an if chain, you could add multiple conditions in the first if – Axnyff Feb 26 '18 at 16:41
  • He means `if (obj1 && obj1.obj2 && obj1.obj2.obj3 && obj1.obj2.obj3.obj4)` but that's ugly as sin. I'd rather see multiple if statements – Reinstate Monica Cellio Feb 26 '18 at 16:42
  • As curiosity, some days ago I discovered a new operator in c# 6 that makes exactly this: obj1?.obj2?.obj3?.obj4?. I haven't found it on javascript yet, but to reduce the pyramid use @Archer comment. – Marc Feb 26 '18 at 16:48
  • @Marc Sadly not available in JS yet, but I use it regularly in C#. The 2 languages get closer every update! :D – Reinstate Monica Cellio Feb 26 '18 at 16:49

1 Answers1

0

You can check them with && operator

if(obj1 && obj1.obj2 && obj1.obj2.obj3 && obj1.obj2.obj3.obj4) {

}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112