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.

3

u/[deleted] May 29 '19

But even Object.freeze won't freeze deeply - i.e,

const obj1 = {
  obj2: {
    foo: "bar"
  }
}
Object.freeze(obj1);
obj1.obj2 = {foo: 'baz'} // noop 
console.log(JSON.stringify(obj1)) // -> {"obj2":{"foo":"bar"}}
obj1.obj2.foo = 'baz' // legal.
console.log(JSON.stringify(obj1)) // -> {"obj2":{"foo":"baz"}}

This is why the Immutable.js library is a thing.

→ More replies (1)