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?