What does the Array.find
method return; a specific copy of a found value or the reference of a found value?
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" }
.
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'))
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
© 2022 - 2024 — McMap. All rights reserved.
array.find
? – Nimwegen.find()
? Your question looks a duplicate of Is JavaScript a pass-by-reference or pass-by-value language?, but I'm not fully convinced. – SacramentalArray.prototype.find()
function. That's just how JavaScript works. See the link I put in my previous comment. – Sacramental