I advocate for learning the damn thing before trying to coerce it. Let’s start with the ELEPHANT of misconceptions…
Yes const is Immutable
const is an immutable primitive value or an immutable reference
If const was to make the “reference object” immutable it would only be practical for the things statically typed OOP languages use const for such as: STATIC_VALUES and config objects.
You can’t refactor const to let but you can refactor let to const
If you change a const to let it has zero impact with the exception of not knowing what values and references are to be mutated. But if you attempt to change all let values to const you may run into errors which is exactly what you want for refactoring. The aim of the game is to reduce mutable values and mutable object references.
const and let together should be immediate indications of assigned vs reassigned
Using const and let together behaves as metadata for healthy code. More information is always ideal. With let and const you are immediately told what is to change and what remains. With just let it’s a paper trail.
Separation of Concerns
Two things to consider:
- What if you want a frozen value with a mutable reference?
- What if you want a partially frozen value with an immutable reference.
For an object based architecture, it makes sense that const and Object.freeze/ seal are separate aspects of the interface.
const forces you to think differently…
How do I simplify my expressions?
What happens from there?
You simplify your logic and resent your old immediate sloppy approaches.
You start using more ternary statements as well as AND and OR operators, you end up converting most of your let declarations to const as you refactor.
Sometimes what required two if statements and 3 let/var variables could be accomplished using 2 or 3 const declarations.
Whatever, I’ll continue to use var
var is not only mutable, it’s re-declarable. So you can do
var a = ‘apple’; var a = ‘banana’;
I know you’re a very clever developer and you like the fact that var can be accessed outside of a block scope. Don’t do it, it’s harder to read in the long run.
Do not use var under no circumstances, unless you must support ES5 and below or play about within a dev console.
Yea but const is not really immutable homie?
Bring the noise ;-)