Does Array.find method return a copy or a reference of the matched element form given array?

Viewed 4714

What does Array.find method returns value some specifical copy of a found value or the reference from the array. I mean what it returns value or reference of the matched element from the given array.

4 Answers

From MDN (emphasis theirs):

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

Whether it returns a copy of or a reference to the value will follow normal JavaScript behaviour, i.e. it'll be a copy if it's a primitive, or a reference if it's a complex type.

let foo = ['a', {bar: 1}];
let a = foo.find(val => val === 'a');
a = 'b';
console.log(foo[0]); //still "a"
let obj = foo.find(val => val.bar);
obj.bar = 2;
console.log(foo[1].bar); //2 - reference

That's a tricky question.

Technically speaking, find always returns a value, but that value could be a reference if the item you're looking for is an object. It will still be a value nonetheless.

It's similar to what's happening here:

let a = { some: "object" };

let b = a;

You are copying the value of the variable a into b. It just so happens that the value is a reference to the object { some: "object" }.

Returns Value

The find() method returns the value of the first element in an array that pass a test (provided as a function).

The find() method executes the function once for each element present in the array:

If it finds an array element where the function returns a true value, find() returns the value of that array element (and does not check the remaining values) Otherwise, it returns undefined

Click Here

Related