It is mainly a coding preference. However, if you are going to use const, you have to know the kind of data that variable will be holding. const will make sure that the variable is unchanged during its entire life once set. However, var can be changed at any point during the variables life.
I would say it’s more than just a preference, it is an accepted best practice now in JS to always use either const or let when declaring variables and only use var when it is absolutely necessary (which is almost never). And that includes using const whenever possible instead of let.
If you want to develop good coding habits then always prefer const except when you know the value of a variable needs to change, then use let.
Yeah, I would call it best practice. var brings with it things like hoisting, function scoping, etc. These can allow sloppy coding (one of JS’s weaknesses, imho).
only use var when it is absolutely necessary (which is almost never) … always prefer const except when you know the value of a variable needs to change, then use let .
That sums it up well.
But just to be clear, the word “change” here is vague. While it holds up well with primitive types, when you get to reference types, you can still change the values to which the variable refers, you just can’t change (reassign) the reference.
const foo = { bar: 41 };
foo.bar = 42; // legal
foo= { bar: 42 }; // illegal
So, unless you need to reassign the reference, you can always use const with reference types. This is how reference types work - the primitive types will work the way you expect.
This is often a source of confusion with beginners.
Yeah, I see that confusion a fair amount to. I haven’t decided what I think is the best way to describe pass by reference without too much confusion over the notion of pointers.
Yeah, I usually just talk about how addresses work and what a reference type is really doing. But FCC tends to shy away from the reading-based learning that something like that needs. FCC seems to shy away from things that can’t be taught in a small code snippet. I mean, the example can be given, but the higher concept would need more of an explanation, I think.