Last active
January 2, 2018 12:05
-
-
Save bkinsey808/b273ab5559af9ba9e944c6bd9037edc4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// suppose I have the following: | |
const x = { a: 1 } | |
x.a = 2 | |
// if I want to make x.a itself sort of like a const, i have to do it like this: | |
const x = {} | |
Object.defineProperty(x, 'a', { value: 1 }) | |
// since that's not the default, so this argument goes, what's the point of const? | |
// as an aside, note that with the Object.defineProperty case | |
x.a = 2 | |
// doest throw an error but doesn't rebind x.a either, so it's actually | |
// different than const where attempting to rebind a const throws an error | |
// another attempt to make const behave like some javascript devs thinks it should | |
// is to use Object.freeze() | |
const x = Object.freeze({ a: 1 }) | |
// but again, | |
x.a = 2 | |
// does not throw an error, so it still isn't really analagous to const | |
// keep in mind one of the biggest benefits of const is that rebinding throws an error | |
// and so helps speed up catching problems. | |
// and Object.freeze isn't a deep freeze. So, | |
const x = Object.freeze({ a: { b: 1}}) | |
//doesn't prevent | |
x.a.b = 2 | |
// and Object.defineProperty has exactly the same issue | |
// the real solution these devs are looking for is probably something like immutable.js | |
const x = Immutable.Map({ a: { b: 1}}) | |
// only in that case | |
x.set(a, {b: 2}) | |
// etc won't work, will throw an error | |
// for me, the easy mental model is to simply remember that | |
// const is not about immutability. | |
// it's just about preventing accidental rebinding. (unrebindability?) | |
// it just so happens that preventing rebinding of primitive types | |
// such as numbers and strings is | |
// essentially the same thing as immutability, yet for arrays and objects, | |
// const only means you can't rebind. | |
// if you want true immutability, use immutable.js. | |
// I'm fine with that, haven't run into any problems. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment