Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
object mutation is not expected from return function

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!