getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
179.26k stars 33.48k forks source link

let for objects? #1764

Closed unnsteinngardars closed 2 years ago

unnsteinngardars commented 2 years ago

This question relates to chapter 2 of the 2nd edition of the first book.

I feel like I need a better explanation on this, why should I use let for declaring an object? What makes sense for me is to use const on an object and if I want it to be immutable, I can freeze it.

It’s ill-advised to use const with object values, because those values can still be changed even though the variable can’t be re-assigned.

If you stick to using const only with primitive values, you avoid any confusion of re-assignment (not allowed) vs. mutation (allowed)! That’s the safest and best way to use const.

getify commented 2 years ago

A lot of people agree with you. I don't. I never, ever use const with a value that's not already immutable. Plain and simple.

I have written more about this topic here (in Appendix A of the 2nd-edition "Scope & Closures" book): https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/apA.md#const-antly-confused

I also have an old blog post archived here that expounds on those thoughts in more detail: https://web.archive.org/web/20150909162102/http://blog.getify.com/constantly-confusing-const/