0

I expected to update a user within users by doing find and setting the the returned value. However, console.log(overview[userI]); does not return print null.

var user = users.find(u => u.id===newUser.id);
var userI = users.findIndex(u => u.id===newUser.id);

user = null;

console.log(overview[userI]);

I then ran the following example:

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
    return fruit.name === 'cherries';
}

let fruit = inventory.find(findCherries); // { name: 'cherries', quantity: 5 }
fruit.quantity = 6;
console.log(inventory);

However, this time inventory is indeed updated as I expected with cherries now with a value of 6.

Why do I not see this behaviour in my first example?

Baz
  • 12,713
  • 38
  • 145
  • 268
  • 1
    In the first example you are reassigning the variable to `null` in the second one you are accessing the referenced object via the variable (and modifying it) – UnholySheep Oct 15 '16 at 18:27
  • Probably because you are trying to do this in some asynchronous code. Provide a [mcve] – charlietfl Oct 15 '16 at 18:30

1 Answers1

1

Assigning null to a variable that previously had an object reference as value, does nothing to that object:

a = { test: 1 };
b = a;
b = null; // this does not influence the value of a.

In the above example, b first is made to share the value of a, but then goes its own way again. Neither of these two assignments changed the value of a.

But when you mutate an object, this will of course be noticed by all references to that same object:

a = { test: 1 };
b = a;
b.test = 2; 
console.log(a.test) // 2

So in your example, if you want your users array to get an element replaced by null, you need to mutate the array:

var userI = users.findIndex(u => u.id===newUser.id);
if (userI > -1) users[userI] = null;

Or, you could also re-assign the complete array with map:

var users = users.map(u => u.id===newUser.id ? null : u);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thanks for your help! How would you replace {name: 'bananas', quantity: 0} in inventory above with {name: 'rotten bananas', quantity: 10} where I use an arrow function to locate banana's after its name: (name) => name === "bananas"? I guess you could use map but wouldn't it nicer if there was an update method for list? – Baz Oct 15 '16 at 18:57
  • Just look how I assigned `null` in my answer and do it with `{ name: 'rotten bananas', quantity: 10 }` instead of `null`. – trincot Oct 15 '16 at 19:02