Baz Baz - 1 month ago 15
Javascript Question

Does List.find return a copy

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?

Answer

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);