0

Let's say I'm implementing a.b.c.d on separate file.

So, I need to check a,b,c is defined and fallback into catch clause when those property is not defined.

Currently, I'm using this code. But it's too long, dirty and hard to maintain.

try{
  if(!("a" in window)) {
    throw new Error();
  }
  if(!("b" in a)) {
    throw new Error();
  }
  if(!("c" in a.b)) {
    throw new Error();
  }
} catch(e){ }

What is the best practice?

Lukabot
  • 189
  • 3
  • 11
  • Do you want to know exactly which one doesn't exist? – Linek Apr 12 '16 at 01:10
  • @Linek What if I say yes? – Lukabot Apr 12 '16 at 01:40
  • You might look at [*Access / process (nested) objects, arrays or JSON*](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json/11922384#11922384). Define "best practice", it depends on your criteria for "best". – RobG Apr 12 '16 at 02:08

2 Answers2

1

You're manually throwing an error in each of those cases, but the behaviour when you try to access a property of undefined is to throw a ReferenceError anyway, so you can just catch that instead:

try{
  a.b.c.d
} catch(e){ // Either a, a.b, or a.b.c was undefined }
Paul
  • 139,544
  • 27
  • 275
  • 264
  • Since you caught the [*error*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error), you can also look at the message, e.g. `Cannot read property 'd' of undefined`. ;-) – RobG Apr 12 '16 at 02:12
-2
if !(a && a.b && a.b.c && a.b.c.d) {
  throw new Error();
}
// else a.b.c.d exists
Wainage
  • 4,892
  • 3
  • 12
  • 22
  • 1
    Except that if `a.b.c.d` exists and has a falsey value, this will throw an error (not my down vote BTW). – RobG Apr 12 '16 at 02:09