Does Array.find method return a copy or a reference of the matched element from a given array?
Asked Answered
I

4

23

What does the Array.find method return; a specific copy of a found value or the reference of a found value?

Ire answered 21/6, 2020 at 10:17 Comment(5)
You mean array.find?Nimwegen
yes and i corrected by post.Ire
What specifically do you mean by "copy"? And why are you wondering this specifically for .find()? Your question looks a duplicate of Is JavaScript a pass-by-reference or pass-by-value language?, but I'm not fully convinced.Sacramental
new instance which does not related to the array which it belongs. Pass by value mainlyIre
@MDJahidHasan JavaScript is pass-by-value, so you will always get a value. But that value could be a reference to an object. But that is completely unrelated to the Array.prototype.find() function. That's just how JavaScript works. See the link I put in my previous comment.Sacramental
L
35

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
Longitudinal answered 21/6, 2020 at 10:20 Comment(0)
N
5

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" }.

Nimwegen answered 21/6, 2020 at 10:26 Comment(0)
N
0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

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

const obj = {}

console.log(obj.find)

const arr = ['a', 'b', 'c']

console.log(arr.find(e => e === 'a'))
console.log(arr.find(e => e ==='c'))
Nitz answered 21/6, 2020 at 10:21 Comment(0)
J
0

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

Jurisdiction answered 21/6, 2020 at 10:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.