Baz Baz - 1 year ago 74
Javascript Question

Does List.find return a copy

I expected to update a user within

by doing find and setting the the returned value. However,
does not return print

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

user = null;


I then ran the following example:

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

function findCherries(fruit) {
return === 'cherries';

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

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

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

Answer Source

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 =>;
if (userI > -1) users[userI] = null;

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

var users = => ? null : u);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download