28. Passing Objects into Functions


#1

here is my code:

// 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
var diff = ageDifference(alice, billy){
return alice.age - billy.age;
}

ageDifference();

the error states I have an unexpected token {

Can someone possibly help me understand why?


#2

I just did the same thing 1 min ago.

Dont change anything about the start code.
Just delete the { return alice.age - bille.age; }

so:

var diff = ageDifference(alice, billy)

#3

so my code must look like this:

// 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
var diff = ageDifference(alice, billy);

ageDifference();

because it doesn't work, the error states :
Oops, try again. It looks like you have an error in your code. Here's the message: TypeError: Cannot read property 'age' of undefined


#4
// 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
var diff =  ageDifference(alice, billy);

This worked for me:)


#5

Thanks for the help, really appreciate it, been stuck for a while now :smile:


#6

no problem man, I just came across your question and I did it 10 secs before haha!


#7

It looks like you're trying to make the "var diff" statement into a function...
delete the {}'s and replace the "return" statement with a "console.log() and I think it'll fly....