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

134
Views
Ignore TypeError during For Loop

I'm trying to figure out how to "ignore" TypeErrors during a For Loop, but I would like to pass an empty string value to my variable when I do come across a TypeError or a property that does not exist. I have tried some try/catch with TypeError, but I'm not quite sure what to do with the catch. Any help is appreciated...

My obj

theObj = [ 
    {
        name:"Billy",
        age:"30",
        level:"10"
    },
    {
        name:"Jimbo",
        age:"25",
        level:"8"
    },
    {
        name:"Ralph",
        age:"37"
    },
    {
        name:"Rita",
        age:"23",
        level:"3"
    }
]

Loop

for (var i = 0; i < theObj.length; i++) {
    const levels = theObj[i]['level']
    console.log(levels)
}

console

10
8
undefined
3

What I would like to see

10
8

3

OR

10
8
Null or some other value like DNE, N/A
3
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

No problem

for (var i = 0; i < theObj.length; i++) {
    const levels = theObj[i]['level']
    console.log(levels ? levels : "")
}
about 4 years ago · Juan Pablo Isaza Report

0

Try theObj[i]?.level, like:

const theObj = [ 
    {
        name:"Billy",
        age:"30",
        level:"10"
    },
    {
        name:"Jimbo",
        age:"25",
        level:"8"
    },
    {
        name:"Ralph",
        age:"37"
    },
    {
        name:"Rita",
        age:"23",
        level:"3"
    }
];

for (let i = 0; i < theObj.length; i++) {
    const levels = theObj[i]?.level;
    console.log(levels)
}

about 4 years ago · Juan Pablo Isaza Report

0

you should try this

const levels = theObj?.[i]?.['level'] || ""

?. make sure that the parent is defined and if not it will return undefined

about 4 years ago · Juan Pablo Isaza 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!