Is there anything wrong with my code?


#1

Section 29:Try it Out!
As per the instructions, I have added olderAge function.

  function Person (name, age) {
        this.name = name;
        this.age = age;
    }

    var ageDifference = function(person1, person2) {
        return person1.age - person2.age;
    };

    var olderAge = function (a,b) {
        if (ageDifference(a,b) > 0) {
                console.log ("a");
                return a.age;
            } else if (ageDifference(a,b) < 0) {
                console.log ("b");
                return b.age;
            } else {
                console.log ("same");
                return a.age;    
            }
    }

    var alice = new Person("Alice", 30);
    var billy = new Person("Billy", 25);

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

Initially, I was having trouble understanding how to write the code. To debug the issues, I have added console.log() in my conditions.
Now, when I run this code, I get the following output:

a
The older person is 30
a
a
b
same

While I understand the first two lines of output, I am not sure about the remaining lines of output.
Can you someone please help me understand where I made the mistake?


#2

I've run your code through a couple of different Javascript interpreters and don't seem to be getting the same results as Codecademy's version - just the first two lines a and 'The older person is 30' as one would expect. I'm not sure why Codecademy's interpreter is doing that.

On a separate note, you could benefit from refactoring your code if you stored the result of ageDifference(a,b) in a variable, then tested that in the if statement:

var olderAge = function(a,b) {
    var difference = ageDifference(a,b);
    if (difference > 0) {
        // Blah blah
    }
    else if (difference < 0) {
        // More blah blah
    }
    else {
        // Even more blah
    } 
}

While it may not really seem a big advantage in this particular case, you'll find in the future that refactored code can save a lot of time if - for example - you wanted to change the function's name or parameters. Imagine if you'd called ageDifference(a,b) a hundred times then decided you wanted to change it to ageDifference(a,b,c)!


#3

@nedwards
Awesome!,
Thanks for your help!
I understand why you want me to refactor the code and it is very useful!
Thanks once again for your help!!