0

I have a problem with a web app I'm creating. In short, I want to pass an array by reference, so that change in a module will affect the array in the main class. The way I do it is:

  1. I send the array as a function parameter and assign it in the module
  2. I trigger the change in the main class, and the array is updated in the module
  3. When I update the array in the module, it is not updated in the main class.

I don't understand it, array should be passed by reference, and apparently it is as the change works one way, but not the other. I log the values on both sides and see that it works. It's driving me nuts...

Code boils down to this, these are the only places where arrays are affected.

Main class:

import { build } from "Module.js";

let usedRelations = [];

window.onload = function () {
build(usedRelations);
}

function addNewRelation(relationId) {
let rel = {}; // instantiating relation object here
usedRelation.push(rel); // it affects the array in the module class
}

Module:

let relationsArray;

export function build(usedRelations) {
relationsArray = usedRelations; 
}

function deleteUnsavedRelation(usedRelation) {

//relationsArray is filtered properly, but usedRelations from main class remain unchanged
relationsArray = relationsArray.filter(x => x.relationId != usedRelation.relationId); 
}
  • 1
    *"I pass an array by reference to another class..."* The term "pass...by reference" has a specific meaning in computer science, and it isn't what you're doing here. (You can't do pass by reference in JavaScript.) What you're doing is passing an object (array) reference, by value, to another module (not class). That means both modules access the same array, to start with. But `filter` creates a **new** array, and assigning to your `relationsArray` variable in the second module has no effect at all on the `usedRelations` variable in the first module. "Pass by reference" refers to passing... – T.J. Crowder Feb 06 '22 at 11:51
  • 1
    ...references to *variables* into functions. JavaScript doesn't have that, it's purely a pass-by-value language. It's just that with objects, the values being passed are references to objects. What you could do in your code instead, is pass an object that has the array as a property. Then, assigning to that property (regardless of which module does that) is seen by the code in the other module also using that object's array property. – T.J. Crowder Feb 06 '22 at 11:53
  • 1
    Thank you @T.J.Crowder, I used an object with the array as a property and it worked. Thank you very much. – SuperMenthol Feb 06 '22 at 12:03

0 Answers0