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

167
Views
Object losing its content after modification in Javascript

I have an object obj1 declared in a file, lets say A.js. I export the object obj1 and copy a local object, say obj2 to another file, say B.js Now, if I export obj1 in a 3rd file, say C.js, I should have the values of obj2 stored in it. But it seems that obj1 is holding the values that it had in A.js

**A.js**
export const obj1 = {};

**B.js**
import obj1 from "A";

//called from main loop
someFunction()
{
Object.assign(obj1,obj2);
//At this point, the obj1 is holding the value of obj2
}

**C.js**
import obj1 from "A";
//obj1 is not holding the value of obj2 any more. 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First of all, there's no strict guarantee of import order in Node.JS. Sometimes B.js loads before C.js, and sometimes – the opposite. But even if you know for sure the import order, that's not something you should rely on, because it might change in the future.

Second, imports are most likely cached, so by the time you get to the second import, it actually imports whatever was imported the first time, – which was the unchanged value.


Most commonly, exported objects are designed to be immutable. You could implement this approach in the following way:

// defaults.js
export const defaults = { foo: 'foo1', bar: 'bar1' };
// merge.js
import { defaults } from './defaults';

export const merge = (overrides) => ({ ...defaults, ...overrides });
// The `defaults` is not mutated
import { merge } from './merge';

const result = merge({ foo: 'foo2', baz: 'baz2' });
// { foo: 'foo2', bar: 'bar1', baz: 'baz2' }
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!