Ante Gulin Ante Gulin - 5 months ago 13
Javascript Question

How to pass by reference (simulation)

I'm having a trouble approaching to this problem, althouh I have a working solution I doubt it is the most optimal one.

Here is the problem:

Imagine an array of objects, each object represents a person.

var people = [
{id:1, name:"John", points: 50},
{id:2, name:"Mark", points: 80},
{id:3, name:"Peter", points: 25},
];


In our people array, we have 3 persons with an unique id property.

Now imagine that we have multiple functions that modify/update person objects.


Obviously this wouldn't work, since the outer object won't be affected
by the changes made in incrementPoints() function.


var myPerson = people[0];

incrementPoints(myPerson){
myPerson.points++;
};

// myPerson.points = 50
addPoints(myPerson); // We're passing an person object to addPoints;
// myPerson.points = 50 (Did not change, not affected by addPoints)



This however, would work! But the price we pay is the cost of
iteration through persons array and matching the id of desired person.


function getPersonIndexById(personId){
// Iterate through all persons in 'people' array
for(var index = 0; index < people.length; index++)
people[i].id === personId ? return index : continue;
}

function incrementPoints(personId){
people[ getPersonIndexById(personId) ].points++;
}

function decrementPoints(personId){
people[ getPersonIndexById(personId) ].points--;
}


Is there a better/simpler/cleaner/intended concept for dealing with such situations. Obviously, the ideal solution would be a pass by &reference but javascript does not allow that. I'm not trying to do achieve an useless hack, but rather get understanding of what developers do when they stumble upon similar situations and how they solve them.

Answer
var people = [
  {id:1, name:"John", points: 50},
  {id:2, name:"Mark", points: 80},
  {id:3, name:"Peter", points: 25},
];

var myPerson = people[0]; 

function incrementPoints(myPerson){
  myPerson.points++;
};

function addPropertyToPerson(myPerson, lastname) {
  myPerson.lastName = lastname;
}

// The properties of the myPerson object can still be modified since 
// the value passed in to the function is the reference to the object
incrementPoints(myPerson);
console.log(myPerson);

// Similarly, additional properties can still be added since 
// the value passed in to the function is the reference to 
// the outer object
addPropertyToPerson(myPerson, "smith"); 
console.log(myPerson);