Could someone pelase explain the mutation behaviour below:
function test () {
let data = {}
const run = () => {
console.log(data)
}
const update = () => {
data = {}
}
return {
container: {
data
},
run,
update
};
}
const { container, run, update } = test();
update(); // run an update to reset value to {}
container.data.test = { result: 'test' }; // try to mutate the data
run(); // it will still return {} instead { data: {test: {result: 'test'}} }
I would expect to update the object would result mutate the data object inside the function., but looks like it's not the case, as if it created a new object.
const { container, run, update } = test();
This creates a new object which includes the current value of the data variable and assigns it.
update(); // run an update to reset value to {}
This changes the value of the data variable to a new object.
container.data.test = { result: 'test' }; // try to mutate the data
This mutates the object that was originally assigned to data and copied to the new object which was returned from test().
It has no effect on the new object that is now the value of data.
In other words:
return { container: { data }, run, update };
… copies the value of data and does not create a reference to the data variable.
When you call the test() function, container.data and data point to the same object:
container.data -----> {} <------ data
but after the following statement:
container.data.test = { result: 'test' };
container.data points to a different object:
container.data -----> { result: 'test' }
data -----> {}
but data still points to the empty object and this data variable is logged by the run() function.
Important thing to know here is that re-assigning to container.data doesn't re-assigns to the data variable as well.