28. Passing Objects into Functions


#1


https://www.codecademy.com/en/courses/spencer-sandbox/4/3?curriculum_id=506324b3a7dffd00020bf661


The code runs, it returns the correct value, but I still get an error message.

Oops, try again. It looks like the value of diff is not a number! Make sure you are setting it equal to ageDifference(alice,billy). Make sure not to put quotes around alice and billy!


// 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 alice.age - billy.age;
}

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

// get the difference in age between alice and billy using our function
ageDifference();
var diff = ageDifference;


#2

you should really use your function parameters:

return person1.age - person2.age

this way, you can use the function for many people, and then when you call the function you can pass alice and billy as arguments:

ageDifference(argument1, argument2);

and store the result of function call in diff (this can all be done in one line)

argument1 and argument2 are just things i made up, please use the proper arguments, if more help is required post an updated version of your code


#3

Thanks for the help. Got it right now (few days of break didn't go well for my learning progress).
This is my code now:

// 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;
}

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

// get the difference in age between alice and billy using our function
ageDifference(alice, billy);
var diff = ageDifference(alice, billy);

https://www.codecademy.com/en/courses/spencer-sandbox/4/3?curriculum_id=506324b3a7dffd00020bf661


#4

nicely done :slight_smile: You also understands why this works?

also, you can remove this line:

ageDifference(alice, billy);

there is no need to call the function twice, you call the function here and store the result directly:

var diff = ageDifference(alice, billy);

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.