Hi all,
I need some help with understanding pass by reference for objects.
let spaceship = {
homePlanet : 'Earth',
color : 'red'
};
let tryReassignment = obj => {
obj = {
identified : false,
'transport type' : 'flying'
}
console.log(obj) // Prints {'identified': false, 'transport type': 'flying'}
};
tryReassignment(spaceship) // The attempt at reassignment does not work.
spaceship // Still returns {homePlanet : 'Earth', color : 'red'};
Above is the example in the course.
I’m still confused as to why the original object, “spaceship” is not changed after calling the function “tryReassignment”.
Instead of
let tryReassignment = obj => {
obj = {
identified : false,
'transport type' : 'flying'
}
};
if we alter the function to be
let tryReassignment = obj => {
obj.identified = false;
obj['transport type'] = 'flying';
}
this would’ve modified the object, and not sure what the difference is.
Sure, instead of re-assigning, now the spaceship will have four keys instead of two as the function originally intended.
[side question: if we want to achieve what the function is originally doing, is the best method to recursively remove all keys and add two?]
In both cases, spaceship object is passed by reference (let’s say memory addr 0x0022) and therefore obj refers to memory address 0x0022.
If we assign new object to that address, regardless of the function knowing “spaceship” variable, it should overwrite that memory space. And next time when we call that memory location, it should return the new data we just put in.
Back to the example, after calling the function and print “spaceship”, not sure why it is unmodified.
Thank you for all your help!