Home > Back-end >  Best way to check an attribute of an object that might be undefined
Best way to check an attribute of an object that might be undefined

Time:07-14

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?

CodePudding user response:

Use Object.hasOwnProperty or Object.hasOwn

 if (oUsed.hasOwnProperty(`x${iX}`) && oUsed[`x${iX}`][`x${iY}`])

or

use like this

 if (oUsed[`x${iX}`] && oUsed[`x${iX}`][`x${iY}`]) {

or if Optional Chaining is supported by your target browser

if (oUsed[`x${iX}`]?.[`x${iY}`]) 
  • Related