let arr = [{ age: 3 }, { age: 5 }, { age: 6 }, { age: 7 }]; let exists = arr.find(x => x.age < 4); exists.age += 1; console.log(arr); //output is [{age:4},{age:5},{age:6},{age:7}];
In the above example, I’m updating the result returned by the find method but it also changes the value of the original array why so?
Advertisement
Answer
It’s because Objects in JavaScript are passed by reference, you got that object ( {age : 3} ) in exists then added 1 to it’s “age” key , so the original object also changed .
let obj1 = {age: 3 , name: 'jack' } let obj2 = obj1 console.log(obj1 === obj2 ) // true // if you change the second object , the first one will change too : obj2.age = 15 console.log(obj1 , obj2 ) // obj1 = { age: 15 , name: 'jack' } // obj2 = { age: 15 , name: 'jack' }