0

Example code:

var person = {
  name: 'Sam',
  age: 45
};

// This function is able to modify the name property
function nameChanger (obj, name) {
  obj.name = name;
}

nameChanger(person, 'Joe');  // modifies original object

But trying to redefine the objection in a similar function doesn't work at all:

var person2 = {
  name: 'Ashley',
  age: 26
};

function personRedefiner (obj, name, age) {
  obj = {
    name: name,
    age: age
  };
}

personRedefiner (person2, 'Joe', 21); // original object not changed

This second example does not modify the original object. I would have to change the function to return the object, then set person2 = personRedefiner(person2, 'joe', 21);

Why does the first example work but the second example does not?

jmancherje
  • 6,439
  • 8
  • 36
  • 56
  • 3
    Do some googling with keywords such as "javascript pass by reference pass by value". Basically, in the first example `obj` is passed in and the function modifies the **inside** of obj. In the second example, you are changing `obj` itself, which will have an effect only inside the function. –  Oct 27 '15 at 17:27

1 Answers1

0

In the second example, you're initializing a new object with scope local to the function.

Jason
  • 2,725
  • 2
  • 14
  • 22