I’m getting the next error in function getOlder():
TypeError: Cannot read property ‘age’ of undefined
What’s the problem and how to fix it?
function person(name, age) {
this.name=name;
this.age=age
}
// Returns the older person in a group of persons.
var getOlder = function(people) {
if (people.length === 0) {
return new person();
}
var older = people[0]; // The first one is the older for now.
var value;
for (var _ in people) {
value = people[_];
if (value.age > older.age) {
older = value;
}
}
return older;
};
// Declare some persons.
var paul = new person("Paul", 23);
var jim = new person("Jim", 24);
var sam = new person("Sam", 84);
var rob = new person("Rob", 54);
var karl = new person("Karl", 19);
var older = getOlder(paul, jim);
if (older.name !== "Jim") {
console.log("Fail");
}
By Accepting no arguments in the function definition and relying on the variable arguments feature of JS you can get away with calling
getOlder(paul, jim).arguments is a property of every function which is basically an array of variable arguments provided to it while calling .