Why must it be coded this way?

Tell us what’s happening:

I have already passed the challenge. My question is, why do I need two statements, instead of just returning the statement that has the .push(friend) ?

userObj.data.friends.push(friend);
return userObj.data.friends;

INSTEAD OF

return userObj.data.friends.push(friend);

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) {
  // change code below this line  
  userObj.data.friends.push(friend);
  return userObj.data.friends;
  // change code above this line
}

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

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object

Look at what push returns. return userObj.data.friends.push(friend) – the value of that is a number

1 Like

That explains it. I had no idea that it automatically returned the length of the array and not the mutated array. THANKS!

1 Like