Even after using strict mode, I am able to update the object variable. How is possible? Is it possible to create constant objects at all?
"use strict";
const x = {a:"sss"}
x.a = "k"
console.log(x)
outputs:
{ a: 'k' }
Okay - so it is required to use Object.freeze call t make the object unchangeable. Even the strict mode isn't required.
const x = {a:"sss"}
Object.freeze(x);
x.a = "k"
console.log(x)
Outputs:
x.a = "k"
^
TypeError: Cannot assign to read only property 'a' of object '#<Object>'
ES6 const
is not about immutability.
const
only creates a read-only reference and that means that you cannot reassign another value for the object.
const
creates an immutable binding
and guarantees that no rebinding
will happen.
Using an assignment operator
on a const variable throws a TypeError exception:
Short example:
const x = {a:"sss"}
x={a:"k"}
console.log(x)
You will see the following message:
"Uncaught TypeError: Assignment to constant variable."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With