Array modification

Tell us what’s happening:
Describe your issue in detail here.
what am I doing wrong here?

  **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 newArr = userObj.data.friends.push(friend);
return newArr;

// Only change code above this line
}

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

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

Challenge: Modify an Array Stored in an Object

Link to the challenge:

Try to console.log(newArr) Just before you return it, see if its what you think it is.

It says undefined. Why is it so?

1 Like

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Array.push does not return an array. newArr is that thing array.push returned.
First example in documentation should answer your question.

2 Likes

Since the length of the array is now 4, you know you have added the friend as there was initially 3. You just need to return the object that contains friends, nothing else.

where have you added it? it should not say undefined

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