2
let courses = [
    {id:1, name : "Femin"},
    {id:2, name : "Darsh"},
    {id:3, name : "Smit"},
];

let enteredId = 2;

const course = courses.find(c => c.id === enteredId);

course.name = "Darsh Bhimani";

console.log(course);
console.log(courses);

So this is the code I've been working with. I have been working with Java and C,C++ for the past 5-6 years and started with Javascript a week back. (For node.js).

Now what I am finding confusing here are two things:

  1. The variable course is a constant, still its value can be changed. How ?
  2. The course is fetched from the array courses, but still on changing course, when I log courses, I see that the value of the array has also changed. How is that possible?

In this case it does not matter if the value changes, but when I don't want the array to change, what can I do?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

2

You get with find an object reference and to break this, you could get a shallow copy of the object with Object.assign. This approach works undefined as well, but returns in that case an empty object.

let courses = [
    {id:1, name : "Femin"},
    {id:2, name : "Darsh"},
    {id:3, name : "Smit"},
];

let enteredId = 2;

const course = Object.assign({}, courses.find(c => c.id === enteredId));

course.name = "Darsh Bhimani";

console.log(course);
console.log(courses);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392