javascriptarrayspass-by-referencepass-by-value

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


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


Solution

  • 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