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?

2
  • 3
    const in JavaScript only means the variable cannot be re-assigned, the properties of objects can still change. Commented Jun 29, 2019 at 18:55
  • with const we can change the properties of the object Commented Jun 29, 2019 at 18:57

1 Answer 1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.