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

Benjamin Bonenfant
Benjamin Bonenfant
4,724 Points

Grateful if someone could lend an eye to help me understand how to add properties to an object in JS...

I need to add a fullName property to an object containing both a firstName and lastName property, though I feel like I'm missing something in my code. Here's what I have at the moment:

function addFullNameProperty(obj) { var fullName = obj['firstName'] + ' ' + obj['lastName']; obj.fullName; return obj; } var names = { firstName: 'Jade', lastName: 'Smith' }; addFullNameProperty(names);

I have tried so many variations of this, I don't know which is even closest now. I know it's a basic thing, but I'm not seeing it. Thanks for your time!

2 Answers

Hi Benjamin -

You are very close. In order to add the fullName property to your object, all you need to do is take the name of your object and add a period, and then the object you are trying to create. For example:

obj.fullName = obj["firstName"] + " " + obj["lastName"];

This can also be accomplished with the following code:

obj["fullName"] = obj["firstName"] + " " + obj["lastName"];

So, when you finish, your code would look like this:

function addFullNameProperty(obj) {
  obj.fullName = obj["firstName"] + " " + obj["lastName"];
}
var names = { firstName: "Jade", lastName: "Smith" };
addFullNameProperty(names);

Hope this helps!

Benjamin Bonenfant
Benjamin Bonenfant
4,724 Points

Thank you for your time, Robert, that was very helpful, just what I needed! Be well.