Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Foundations Objects Call and Apply

Object produces wrong output from Function.

I am frankly quite lost here as I have problems applying what I saw in the instruction video to a code challenge. The video talks about call and apply - but apparently I don't really understand where to use either of them here.

The task: "'The 'greeting' variable should be 'Hello Michael, my name is Andrew and I am in a awesome mood!'."

My code looks like this:

  var genericGreet = function(name, mood) {
    name = name || "you";
    mood = mood || "good";
    return "Hello " + name + ", my name is " + this.name +
      " and I am in a " + mood + " mood!";
  }

  var andrew = {
    name: "Andrew"
  }

  var args1 = ["Michael", "awesome", ":)"];

  var greeting = genericGreet({name: "Andrew"}, args1);

The last line includes the problem. Even after trying various things I cannot get the right output (and the error messages don't rely help to figure out the problem).

Thanks for any help! :)

2 Answers

Hey Max,

Couple issues. Well, one issue, really. You forgot to call the apply method.

Your answer:

var greeting = genericGreet({name: "Andrew"}, args1);

Should be:

var greeting = genericGreet.apply({name: "Andrew"}, args1);

Also, I think they're asking you to pass in the predefined andrew object, as opposed to creating an object within the apply method, but either way will result in the correct answer.

Here it is with the predefined andrew object in place:

var greeting = genericGreet.apply(andrew, args1);

Thank you, Nathan! Your code solved the problem and my misunderstanding.

Anytime! Glad I was able to help!