Best way to check an attribute of an object that might be undefined

Viewed 35

I have an object (oUsed) containing "blocked" fields of a grid. If a field is blocked, it's "true". If it's not blocked, it's undefined.

What can happen now is, that a whole line (x coordinate value) is not blocked. So the following code will fail, as it checks the attribute of an undefined object.

    let oUsed = {
      "x1":{
        "y2": true; 
        "y3": true;
      }
      "x3":{
        "y2": true;
      }
    }
    let iY = 2;

    for (let iX=1;iX <= 3; iX++) {
        if (oUsed[`x${iX}`][`x${iY}`]) {
          break;
        }
    }

Doing it in two steps works, but it's not very pretty.

    for (let iX=1;iX <= 3; iX++) {
      if (oUsed[`x${iX}`]) {
        if (oUsed[`x${iX}`][`x${iY}`]) {
          break;
        }
      }
    }

What's the best practice for this kind of check?

1 Answers
Related