My code for 29. Try it out! keeps returning "undefined"


#1

Every time I run the below code, "The older person is undefined" to the console and I get the error message "Oops, try again. Your olderAge function seems to be returning something other than a number. The function should return the AGE of the older person." Except I can't seem to find the problem. Please help!
https://www.codecademy.com/en/courses/spencer-sandbox/4/4?curriculum_id=506324b3a7dffd00020bf661

// Our person constructor
function Person (name, age) {
    this.name = name;
    this.age = age;
}

// We can make a function which takes persons as arguments
// This one computes the difference in ages between two people
var ageDifference = function(person1, person2) {
    return person1.age - person2.age;
};

// Make a new function, olderAge, to return the age of
// the older of two people
var olderAge = function (person1,person2) {
    if (person1 > person2) {
        return person1.age;
    } else if (person1 < person2) {
        return person2.age;
    }
}

// Let's bring back alice and billy to test our new function
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);

console.log("The older person is " + olderAge(alice, billy));


#2

Interpreter does not know what you mean in this line:

person1 > person2

You have to define how you would like to compare two Person objects or compare other values (hint... age) :slight_smile:


#3

Ohhh thanks I didn't catch that!


#4

You're very welcome :slight_smile:


#5

Just a small extra note.

Codecademy does not teach anything about operator overriding, but if you would like to make Person objects comparable you can override method valueOf, like this:

Person.prototype.valueOf = function() {
    return this.age;
};

And now your previous code should work. This is a nice concept, especially useful when you can transform object of your class into a single numerical value.