0

I have question about consts/lets in JS and mutable objects.

Basically, should I use const to declare objects eg. Arrays that are able to mutate with .push? Is not that the consts should stay as they were declared, without any mutation and if there is one, it should be declared with let?

The vast majority projects uses Eslint rules to force const over let when value is not reassinged. Is there any benefit of using const?

What I found is this article but it still not solving my problem Should I declare mutable objects with const

jac0b95
  • 13
  • 5
  • Absolutely, if the variable name doesn't get reassigned. Mutation is completely different. – CertainPerformance Oct 22 '21 at 21:22
  • That clear for me, but in C++ or event PHP class const can not be mutated when declared with const. It's a bit confusing when some languages allows to mutate variables and some not. Shouldn't we keep in mind to declare objects that mutates with let to follown good practices ? – jac0b95 Oct 22 '21 at 21:38
  • Use `const`. `const` does not care for the inner keys (unless they are frozen). `const` is there to assure no later assigmnent `=` is performed over that *in-variable* or the same name is used. So if you have `const ob = {a:0}` you cannot later do `ob =`. That does not means you cannot modify the contents of your unfrozen Array or Object. But you can always use (if you don't want to go one-by-one Object property) the handy `Object.assign(ob, {a:1,b:2});` which will give you `{a:1, b:2}` even if `ob` was defined as const. Or go the old way: `ob.a=1; ob.b=2` – Roko C. Buljan Oct 22 '21 at 21:40
  • Use `const` in JavaScript as it means for JavaScript, not for PHP or some other language. – CertainPerformance Oct 22 '21 at 21:40
  • You are right, but it's not reffering to problem. Keyword `const` brings ffirst thought that not only instance/memory reffernce, but also value of assigned object can not be changed. Those differences are little bit wierd between languages. But even if some language allows us to do such a things should we do that or just do it "the right way"? PS. I know that `const object = Object.freeze({ a: 1 })` is kind a C++ `const` – jac0b95 Oct 22 '21 at 22:07

0 Answers0