0

if i have an object like a.b.c.d = "exists" and i want to check if (a.b.c.d){..} is true.

Then how can i do it without getting an error. if obj a doesn't exist. I get an error and program stops. I want program to continue and if obj a or b or c or d don't exist, just it should evaluate to false.

it makes sense if a doesn't exit then so doesn't d, why does browser give an error here? And how can i fix this i certianly don't want to do this: if (a && a.b && a.b.c && a.b.c.d) {..}

Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168
  • 1
    The example you gave of what you don't want to do is actually a fairly common practice, though often not necessary to so many levels. – James Montagne Feb 23 '15 at 21:08
  • is there a function that could do this: so i can write `if ( exists(a.b.c.d)) {..}` – Muhammad Umer Feb 23 '15 at 21:09
  • 1
    Wrap your if statement in a try...catch block – Alex Hill Feb 23 '15 at 21:10
  • 2
    FWIW, there are talks about an "existential" operator for ES7 (or later), that could look like `a.?b.?c`, but that's still quite a bit in the future. – Felix Kling Feb 23 '15 at 21:11
  • good to know, and i have been thinking of try catch, but i was wondering if there existed a way because seems important to be able to check such stuff – Muhammad Umer Feb 23 '15 at 21:12
  • It's certainly better to check than to use try/catch for this type of work. Exceptions are meant to be exceptional, not things you can routinely test for. The dupe question has a couple of good answers. – James Thorpe Feb 23 '15 at 21:13

0 Answers0