by russellbeattie · 6y ago · 0 comments
(I don't care if I get a million down votes, I really don't. You're all misusing const and you know it. It's a shitty hack turned into a fad by someone who didn't understand the language.)
Also, in general, using the most limited constructs that fit your use case makes a tonne of sense for code cleanliness, in any language. For example, in a language supporting private/protected/public properties and methods, you should always default to private, as that’s most limited and easiest to reason about. Then make it more public as necessary. Same goes for const vs. let - const is more limited, it’s a better default choice, only use let if you actually need to re-assign it. Using const means there’s one less thing for readers of the code to worry about, it’s a variable that CAN’T be reassigned, the same way you don’t have to worry about a private method being called externally.
This is, essentially, the “principle of least power.”
Also, if you’re talking about leaving mutability like this in the code long term, this really only applies to GLOBAL mutable state, and global mutable state is a terrible thing for code maintainability in any language. If it’s not global, you can’t fiddle with it later in the console anyways. Littering your program with global mutable state just because “someday, someone may want to fiddle with this in the console, and this makes that slightly easier”, that’s just not a reasonable argument.
You're welcome to go use another language that doesn't have a formal spec, if you're so inclined to disagree with what the spec for this one says.
const improves readability, and the ability to reason about code. It lessens the need to exhaustively scan the code looking for other assignments to the variable.
const foo = {};
foo = 42; //not allowed
foo.bar = 'baz'; //this is fineIt’s the same behaviour in many other languages.
Why would rebinding variables ever be a good thing?
const fixed the pointer but don't prevent user change the value in the storage it point to.
It is possible to define a pointer to an object whose contents may not be changed. This is done with ‘const * type object’.
If you want a pointer whose value must not change, but do not care about the contents of the pointed to object, you would write ‘type * const object’.
This is a pointless discussion.
const foo = #{};
foo = 42; //not allowed
foo.bar = 'baz'; //not allowed
https://2ality.com/2020/05/records-tuples-first-look.html