Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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}`]) 
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!