Benefit of const vs let in TypeScript (or Javascript)

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.


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.