Biketire
Biketire

Reputation: 2069

Can these nested 'if typeof(bla) else' statements be done shorter?

I have a piece of code that goes like this. This piece of code works but it looks horrible.

if(typeof(d.object) != "undefined"){
  if(typeof(d.object.property) != "undefined"){
    if(typeof(d.object.property.length) != "undefined"){
      // do the code
    }
    else alert("error");
  }
  else alert("error");
}
else alert("error");

Is there any way this can be rewritten so it does the same but more efficient. Especially because the errors are all the same.

Upvotes: 2

Views: 209

Answers (3)

Grim
Grim

Reputation: 1976

Good suggestions,

this is a job for a function!

function has(v){return typeof(v) !== "undefined";};

if(has(d) && has(d.object) && has(d.object.property) && has(d.object.property.lenth)) {
   ...
} else alert("error");

Regards

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382122

Supposing you're not interested in the property if its length is null or 0 (or more generally "falsy" as suggested by Jan Dvorak), then you might make it a little more readable even without using try/catch :

if (d && d.object && d.object.property && d.object.property.length){

} else {
   alert('error');
}

in most cases this is the way to go.

About the "falsy", from the MDN :

Any value that is not undefined, null, 0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement

Upvotes: 7

user1726343
user1726343

Reputation:

try{
    if(typeof(d.object.property.length) != "undefined"){
      // do the code
    }else{
      throw "Value undefined";
    }
}catch(e){
    alert("error");
}

This works as long as you're just refactoring some code that you know works, but it makes debugging harder.

Upvotes: 2

Related Questions