I keep making this mistake

Hey guys, I just solved this one but kept making the mistake of including user into the equation. I guess my thinking was that since data.friends is part of user then it would be included.

Turns out userObj is replacing it. Can you explain this part? Thanks

Your code so far


let user = {
name: 'Kenneth',
age: 28,
data: {
  username: 'kennethCodesAllDay',
  joinDate: 'March 26, 2016',
  organization: 'freeCodeCamp',
  friends: [
    'Sam',
    'Kira',
    'Tomo'
  ],
  location: {
    city: 'San Francisco',
    state: 'CA',
    country: 'USA'
  }
}
};

function addFriend(userObj, friend) {
// Only change code below this line
userObj.data.friends.push(friend);
return userObj.data.friends;
// Only change code above this line
}

console.log(addFriend(user, 'Pete'));

// Finish writing it so that it takes a user object and adds the name of the friend argument to the array stored in user.data.friends and returns that array.


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36.

Challenge: Modify an Array Stored in an Object

Link to the challenge:

If I understand, user is included. It’s just passed in. Here,

addFriend(user, 'Pete')

This is passing the reference, the address that points to the data, into that function in the first parameter. Remember that because it is a reference type, user does not hold the data, just the address of the data.

Now in the function, that address is accepted:

function addFriend(userObj, friend) {

So, now there are two variables that contain the reference to that data - user in the outer scope and userObj inside the function. Changes to the data of either will affect the other because they are both pointing to the same place in memory.

Could you have used user inside the function instead of passing the reference in? Sure. But there could be problems with that.

  1. Then that would only work for that one user. What if you had thousands of users. Are you going to create a separate function for each? Or you could write one function that accepts the reference to the “user” to whom you want to add.

  2. There is an idea that it is not good practice to have global variables. It may not seem like much now, but this will get important, having pure functions that don’t depend on data that is not passed into them. Sometimes you do with with constants, but should not do this with variable data.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.