const stands for constant, and it means the variable cannot be reassigned at a later time.
let is similar to var except that it is block scoped, which means it can be declared inside of a for loop and will be local to the body of that for loop (and therefor does not exist outside of it)
The latter is different from a var variable which can be declared anywhere but is always local to the function scope.
In general it is good practice to try and define your variables as const as much as possible.
const stands for constant, and it means the variable cannot be reassigned at a later time.
let is similar to var except that it is block scoped, which means it can be declared inside of a for loop and will be local to the body of that for loop (and therefor does not exist outside of it)
The latter is different from a var variable which can be declared anywhere but is always local to the function scope.
In general it is good practice to try and define your variables as const as much as possible.
As I meanwhile do almost exclusivey functional programming I find the destinction between const and let pretty useless.
I never ever reassign values to names. Never - regardless of the language.
Having said that I find the usage problematic due to 2 reasons.
constis longer thanlet(no seriously!)constsort of communicates back: Hey! I am constant but that is not true (well it is, but ...) I had multiple times collegues that were totally surprised
that this is possible
const x = { foo: "bar" }
x["foo"] = "Not bar!"
Sure the name and its reference is const but the object referenced is not. Granted in Typescript you can at least create
type ROO = Readonly<SomeType>
const x: ROO = someReferenceValue
x.someProp = "A wanna be a bar!" //compile error
So for Typescript const finally could mean const
TypeScript/ES2015: Prefer `const` instead of `let` reduces readability?
JS <> const vs let = should I always use const?
Benefit of const vs let in TypeScript (or Javascript) - Stack Overflow
How much should I be using 'let' vs 'const' in ES6?
Videos
I confuse the following term var, const, let in typeScript and when should I use them?
*sigh*... This is why immutable needs to be the default. Even the referenced Java answer suggests this. Note that that answer does not recommend removing final modifiers, just that the author of that answer wouldn't add them in new code (for local variables) because they "clutter up" the code.
However, there is a difference between JavaScript and Java here. In Java, final is an additional modifier on a variable declaration, so you get:
final int foo = 3; // versus
int foo = 3;
In JavaScript, though, const is just an alternate variable declaration, so the situation is:
var foo = 3; // (or let nowadays) versus
const foo = 3;
I don't think two more characters constitutes "clutter". If the alternative being suggested is just foo = 3 then the reviewers are just wrong.
Personally, I would always use const when applicable and would suggest it's inclusion in a code review. But then I'm a Haskeller, so I would be like that. But also, JavaScript tends to be more pervasively mutable and have a worse debugging story when things do unexpectedly change, that I would say const in JavaScript is more valuable than final in Java (though it's still valuable there.)
As Ixrec points out, const only controls the modifiability of the binding, not the object that is bound. So it's perfectly legal to write:
const foo = { bar: 3 };
foo.bar = 5;
This can be used as an argument against using const as someone may be surprised when an "unmodifiable" object is modified. Newer versions of JavaScript do have a mechanism to actually make objects unmodifiable, namely Object.freeze. It makes a good addition to const (though only use it on objects that you create, for example, as Object.freeze({ ... })). This combination will communicate and enforce your intent. If used consistently, the times where you are mutating things will stick out and clearly signal non-trivial data flow.
It is indeed good practice to declare variables as const (or readonly or final, depending on the language) if possible.
The author of the linked answer also admits that is is right to mark variables as final, but the author is simply too lazy to do it.
Even if the authors opinion about "clutter" was right, then it wouldn't apply to JavaScript or TypeScript, since const is instead of let, not in addition to.
Since we can change the value of const by changing the object it is pointing to, then is it preferable to always use const? I'm probably getting a little ahead of myself, but I was just curious.
I agree with Giorgi that performance is not the main reason. A code analyzer could just as well determine that a variable declared with let is not ever reassigned and optimize it the same as if you had declared it with const. (Heck, linters have rules to detect this and suggest using const instead of let.)
Yes, it does signal to the reader that you're not going to assign to the variable. The benefit of const, over putting a comment saying the same thing, is mainly that const is a standard way of signalling it. Being standard, it transmits the information more readily than custom comments. (Also, a comment could be wrong but const won't let you be wrong.) I don't think this is the main benefit though.
The "principle of least privilege" is often invoked in conjunction with const, but why should I care about the least privilege? Because it helps with early detection of coding mistakes. Consider the following code:
function findSomethingInDocument(document) {
let tree = getTreeFromDocument(document); // We get some sort of tree structure.
let found;
for (const child of tree.children) {
if (child.someFlag) {
tree = child; // Oops I meant found = child :(
break;
}
}
return found;
}
In this code, I typed tree = child when I meant to type found = child. Yes, the bug can be found in testing. But why wait for testing? I never meant tree to be changed. If I had marked it const then I would have immediately learned the error because the compiler would informed me of it. I would not have to wait for testing. The code above is fairly simple but imagine a more complicated algorithm that uses more variables.
When you have a variable which can be declared as const, and you declare it as such you inform the reader that you don't plan to reassign it to a different value later on.
Also by declaring a variable const it means you have thought up front that you don't plan to reassign it, which in turn can protect you from accidental bugs or errors.
My reply here is not javascript-specific.
As a rule of thumb in any language that lets me do so in a semi-easy way I'd say always use const/final/readonly/whatever it is called in your language whenever possible. The reason is simple, it's much easier to reason about code when it is dead obvious what can change and what cannot change. And in addition to this, in many languages you can get tool support that tells you that you are doing something wrong when you accidentially assign to a variable that you've declared as const.
Going back and changing a const to a let is dead simple. And going const by default makes you think twice before doing so. And this is in many cases a good thing.
How many bugs have you seen that involved variables changing unexpectedly? I'd guess a lot. I know that the majority of bugs that I see involve unexpected state changes. You won't get rid of all of these bugs by liberally using const, but you will get rid of a lot of them!
Also, many functional languages have immutable variables where all variables are const by default. Look at Erlang for example, or F#. Coding without assignment works perfectly in these languages and is one of the many reasons why people love functional programming. There is a lot to learn from these languages about managing state in order to become a better programmer.
And it all starts with being extremely liberal with const! ;) It's just two more characters to write compared to let, so go ahead and const all the things!
Be careful, because const object keys are mutable.
From here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
object keys are not protected
consider this example:
const colors = {red: "#f00"};
console.log(colors); // { "red": "#f00" }
colors.red = "#00f";
colors.green = "#0f0";
console.log(colors); // { "red": "#00f", "green": "#0f0" }
Same thing for arrays:
const numbers = [1, 2, 3];
console.log(numbers); // [ 1, 2, 3 ]
numbers.push(4);
console.log(numbers); // [ 1, 2, 3, 4 ]
I haven't decided totally myself, but I'm considering using const for all non-array/non-objects and use let for objects/arrays.