r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

16

u/magical_h4x May 28 '19

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.

1

u/MeowTooMovement4Cats May 28 '19

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