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" ?
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);
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];
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);