2
const courses = [
    {'id':101,'name':'Complete Web Dev'},
    {'id':102,'name':'DS and Algo'},
    {'id':103,'name':'React'}
];

let num = courses.find(c=>{
  if(c.id===102)
    return c;
});

num.name="Programming Fundamentals"
console.log(courses);

Can anyone please explain to me that when I am changing the value returned from the find function then why do the values inside the original array changes? Is there a concept that I am missing? After executing the code I am getting the below-mentioned output.

[
  { id: 101, name: 'Complete Web Dev' },
  { id: 102, name: 'Programming Fundamentals' },
  { id: 103, name: 'React' }
]
  • 2
    Short anser: simple types are 'call by value' whereas objects and arrays are 'call by reference' – nilsK Apr 13 '21 at 11:14
  • 1
    Does this answer your question? [JavaScript by reference vs. by value](https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value) – nilsK Apr 13 '21 at 11:14

1 Answers1

1

It is because you are referencing the same object. In JavaScript only the primitive values get passed by value. If you want it to be a different object then you can copy it.

One way of doing that is spreading the object and assigning it again.

num = {...num}

Keep in mind that spreading an object is a shallow copy, meaning that if you have a nested object then it won't be copied but referenced.

Dokanix
  • 56
  • 1
  • 5