Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;
?
However, if I use bracket notation like return contacts[i][prop];
, it works fine and returns the property of the object.
By the way, this code snippet is from one of the lessons at freecodecamp.org
Below is the code sample :
var info = [
{
"name": "John",
"age": 30,
"city": "New York"
},
{
"name": "Alice",
"age": 25,
"city": "Los Angeles"
}
];
function displayInfo(name, property){
for (var i = 0; i < info.length; i++){
if (info[i].name === name ){
if (info[i].hasOwnProperty(property)){
return info[i].property; // This will return the property value
}
else{
return "Property not found";
}
}
}
return "Name not found";
}
console.log(displayInfo("John", "age"));
console.log(displayInfo("Alice", "city"));
console.log(displayInfo("Bob", "age"));