Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialvictor guia
8,098 PointsHelp on Javascript Objects Code Challenge
Hello,
I am having trouble with this code challenge. Below is my solution which returns an error:
var genericGreet = function() {
return "Hello, my name is " + this.name;
}
var andrew = {
name: "Andrew",
greet: genericGreet()
};
var ryan = {
name: "Ryan",
greet: andrew.greet
};
Hoping someone can help me. Thank you.
4 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi Victor,
You don't want to call the genericGreet function with the parentheses. You simply want to set the greet method to that function.
var genericGreet = function() {
return "Hello, my name is " + this.name;
}
var andrew = {
name: "Andrew",
greet: genericGreet
}
var ryan = {
name: "Ryan",
greet: genericGreet
}
Michael Hinrichs
10,920 PointsHey Victor, what is the error?
victor guia
8,098 PointsThanks Jason. That was the correct solution. But shouldn't we always call a function with ()?
Jason Anello
Courses Plus Student 94,610 PointsYes, you would use () whenever you want to call and have a function executed.
But at that point all it wants is for you to assign the function to the greet
method. You don't want the function to be called and executed at that point.
You can later call the method like this: andrew.greet()
Here I have used the () because I want to call this method now and have it executed.
If you do use () where you tried then the function will be executed when that code is reached and the return value of that function is what will be assigned to greet
. So instead of greet
being a method that stores a function it will be a property that stores a string since that function returns a string.
victor guia
8,098 PointsOk got it. Thanks so much.