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" ?
CodePudding user response:
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);
CodePudding user response:
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];
CodePudding user response:
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);
CodePudding user response:
Use try...catch blocks to catch the errors and handle them as needed (surround anything you think might throw errors):
var animals = {
"mammals": ["Cat", "Dog", "Cow"]
};
var groupA = animals.mammals[0];
var groupB = animals.birds;
try {
var groupC = animals.birds[0];
} catch (error) {
console.error(
"'animals.birds' is undefined, so we cannot access property '0'."
);
}
console.log(groupA);
console.log(groupB);
console.log(groupC);
CodePudding user response:
In second case:
birds
itself is undefined on the object animals.
Accesing property of undefined is throwing the error.
It is like doing undefined[0]
.
Use optional chaining
var animals = {
"mammals": ["Cat", "Dog", "Cow"]
};
var groupA = animals.mammals?.[0];
var groupB = animals.birds?.[0];
console.log(groupA);
console.log(groupB);