Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 452
MdJahidHasan009 Avatar asked Jun 21 '20 10:06

MdJahidHasan009


People also ask

Does array find return an array?

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

Are arrays copied by reference in JavaScript?

Array/object values are copied by reference instead of by value.

Which method of the array removes and returns?

JavaScript pop() Method: The pop() method is a built-in method that removes the last element from an array and returns that element. This method reduces the length of the array by 1. Syntax: array.

How do you find a matching element in an array?

To find the first array element that matches a condition:Use the Array. find() method to iterate over the array. Check if each value matches the condition. The find method returns the first array element that satisfies the condition.


1 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
like image 57
Mitya Avatar answered Sep 23 '22 11:09

Mitya