Why when I change x variables, the property 'friends' also change although I didn't do anything

Tell us what’s happening:
Describe your issue in detail here.
why when I change x variable, the property ‘friends’ also change simutaneously although I haven’t pass the value of x to property ‘friends’ again yet.
Thanks for helping.

  **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
let x = userObj.data.friends;
x.push(friend);
return userObj.data.friends
// Only change code above this line
}

console.log(addFriend(user, 'Pete'));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

Challenge: Modify an Array Stored in an Object

Link to the challenge:

Objects and arrays will be stored using references and not by values. So try to use spread operator (ES6 feature). By using this, you will be doing a shallow copy of your object. So the main object properties won’t get effected.

function addFriend(userObj, friend) {
// Only change code below this line
let x = [...userObj.data.friends,friend];
console.log(x);
return userObj.data.friends
// Only change code above this line
}

Hi, the answer is simple you haven’t copied the friend’s array instead you have directly changed the values in the array as arrays and objects are stored using their reference.

thank you for your help

is that mean if I set “let x = userObj.data.friends” it’s also equal to “userObj.data.friends = x” ?

I got it. Thanks for your hint. Object references and copying

It’s like saying A = 5 it’s also equal to 5 = A they are not the same, but in let x = userObj.data.friends it won’t make any sense if you used userObj.data.friends instead of replacing it with variable x in the code. Why would someone ( beginners mistake ) assign a value to a variable and then never use it, here the variable will be called an unused variable

If you use:

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

Your code will definitely run, but it’s not recommended ( as it doesn’t make any sense ).

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