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 trial

JavaScript JavaScript Foundations Objects Methods

victor guia
victor guia
8,098 Points

Help 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

Hi 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
      }
victor guia
victor guia
8,098 Points

Thanks Jason. That was the correct solution. But shouldn't we always call a function with ()?

Yes, 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
victor guia
8,098 Points

Ok got it. Thanks so much.