-2

enter image description here


Why myVariable can be modified?


const obj = {
    a: 'a'
}
const myVariable = obj;

try{
    myVariable = { a: 'c' } //The const declaration creates a read-only reference to a value
}catch(e){
    console.log(e);
}

myVariable.a = 'b';

console.log(myVariable); //{a: "b"}
  • because it's teh same object – Jaromanda X Jun 28 '18 at 05:43
  • object pointed by both const is the same.Objects are copied by reference instead of by value – Aravind S Jun 28 '18 at 05:45
  • `const` just ensures that the variable cannot be reassigned. Changing a property of an object does not reassign the value of the variable (it is the same reference) so what you have indicated will work. If you wanted to make sure no more properties are added/modified you could explore [`Object.freeze`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) – Chirag Ravindra Jun 28 '18 at 05:49
  • 1
    if you want, you can `Object.freeze(obj)` - then it's frozen - not deeply though – Jaromanda X Jun 28 '18 at 05:50
  • 2
    You are mixing/confusing (im)mutable **bindings** (variables) with (im)mutable **values**. They are two different things. `const` makes the binding immutable, not the value. – Felix Kling Jun 28 '18 at 10:12

1 Answers1

1

This happens because your constant is actually storing a reference to the object. When you're adding to object you're not re-assigning or re-declaring the constant,you're just adding to the "list" that the constant points to.Refer more here : Why can I change value of a constant in javascript

Aravind S
  • 2,347
  • 2
  • 12
  • 21