Object re-assignment in functions

Why is it thaat when you re-assign an object in a function and log it in the global scope, the object doesn’t change?

1 Like

Because the object is not the thing in the argument/parameter. Only its reference is given. When we make changes to the aliased object in the function, we’re actually making changes to the real object. References are like business cards. They can be passed around. They all still, by whatever name we give them, refer to the same object.

2 Likes

To piggyback off of @mtf’s great description and analogy, there are ways around this that would allow you to replace the globally scoped object. In keeping with the business card analogy, it would be equivalent to scratching everything out and writing other notes on the card.

One way of doing it would be to use Object.keys() to get an array of the object’s keys to iterate through and delete, then using Object.assign() to add new keys/values to the object to avoid re-assigning the reference.

Here is an example:

const globalCard = {
  fullName: 'Mr. Select All',
  company: 'Codecademy Forums',
  specialties: ['Learning', 'Teaching', 'Living']
};

const testReplacement = (obj) => {
  // delete all existing keys but not the object reference itself
  Object.keys(obj).forEach(key => delete obj[key]);

  //
  // obj (and globalCard) would now be an empty object
  //

  const notes = {
    todo: ['Check on Aunt Edna', 'Take Smudge to vet'],
    reminder: 'Birthday is coming up'
  };

  // give it new keys / values by targeting the existing object reference
  // without replacing it
  Object.assign(obj, notes);
};

console.log(globalCard);
testReplacement(globalCard);
console.log(globalCard);

would produce:

{
  fullName: 'Mr. Select All',
  company: 'Codecademy Forums',
  specialties: [ 'Learning', 'Teaching', 'Living' ]
}
{
  todo: [ 'Check on Aunt Edna', 'Take Smudge to vet' ],
  reminder: 'Birthday is coming up'
}

Note also that if you were sure both objects had the same property names, you could skip the step where we iterate through and delete the existing keys since Object.assign() would replace each value anyway.

1 Like