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

215
Views
How to escape an error when accessing a non-existent key with an ordinal number

The result of the code below is Cat and undefined. *If the key does not exist, the result will be "undefined".

   var animals = {"mammals":["Cat","Dog","Cow"]};
   var groupA  = animals.mammals[0];
   var groupB  = animals.birds;
   console.log(groupA );
   console.log(groupB);

However, The result of the below code is "error" instead of "undefined".

*Uncaught TypeError: Cannot read properties of undefined (reading '0')

var animals = {
  "mammals": ["Cat", "Dog", "Cow"]
};
var groupA = animals.mammals[0];
var groupB = animals.birds[0];

console.log(groupA);
console.log(groupB);

If the key have an ordinal number which doesn't exist, How to get an "undefined" ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use optional chaining

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

var animals = {
  "mammals": ["Cat", "Dog", "Cow"]
};
var groupA = animals.mammals?.[0];
var groupB = animals.birds?.[0];

console.log(groupA);
console.log(groupB);

about 4 years ago · Juan Pablo Isaza Report

0

You need to evaluate the attribute first, see below:

var animals = {"mammals":["Cat","Dog","Cow"]};
var groupA  = animals.mammals[0];
var groupB  = (animals.birds || [])[0];
about 4 years ago · Juan Pablo Isaza Report

0

You could check for the property and explicitly set that value with a ternary:

var animals = {
  "mammals": ["Cat", "Dog", "Cow"]
};
var groupA = animals.mammals ? animals.mammals[0] : undefined;
var groupB = animals.birds ? animals.birds[0] : undefined;

console.log(groupA);
console.log(groupB);

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!