A lot of devs coming from other languages assume const means constant value, whereas it's actually simply constant reference (i.e. can't reassign that variable).
You can't do
const a = 1
a = 2 // error!
but this is fine
const obj = {}
obj.newProp = 1
Check out Object.freeze if you want to prevent the value (objects, specifically) from being changed.
Nice! But why is it called constant by reference? In other languages like C++ you can’t reassign the constant variable nor can you change the property of the object it is assigned to whether it is constant reference or constant value?
struct Ob { int i = 0;};
const Ob foo;
foo.i = 1; //error
foo= Ob(); //error
Ob bar;
const Ob &zoo = bar;
zoo.i = 1; //error
16
u/magical_h4x May 28 '19
A lot of devs coming from other languages assume
constmeans constant value, whereas it's actually simply constant reference (i.e. can't reassign that variable).You can't do
but this is fine
Check out Object.freeze if you want to prevent the value (objects, specifically) from being changed.