I agree with Giorgi that performance is not the main reason. The code analyzer could also pinpoint that a variable declared with let is never reassigned and will optimize it just as if you had declared it with const . (Heck, lintra have rules to detect this and suggest using const instead of let .)
Yes, this signals the reader that you are not going to assign this variable. The advantage of const over a comment saying the same thing is basically that const is the standard way of signaling. Being standard, it conveys information more easily than user comments. (Also, the comment may be wrong, but const will not allow you to make a mistake.) I do not think this is the main advantage, though.
The principle of least privilege is often invoked along with const , but why should I care about least privilege? Because it helps with early detection of coding errors . 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 wanted to type found = child . Yes, the error can be found during testing. But why wait for testing? I never wanted a tree change. If I noted its const , I would immediately recognize the error, because the compiler informed me of this. I would not have to wait for testing. The above code is pretty simple, but imagine a more complex algorithm that uses more variables.
Louis source share