Usage of var, let and const in Javascript

We require ES6 for sao. This means that we can use let and const instead of var to declare variables.
The scoping of var makes it more error prone and difficult to use but we have a legacy usage of it.
Now we start to use let and const for new code which often simplify and make the code more readable.

But I would like to rule on the usage of const which is often see as immutable constraint but it is not. It only forbid reassignment.
So it is common on internet to find recommandation to use it as much as possible. But I do not think it is a good way for long term maintenance.
For example we have started to use this kind of pattern:

for (const i of array) {
   ...
}

but if later we need to reassign the variable i to fix a problem the change will be:

- for (const i of array) {
+ for (let i of array) {
    ...
+   i += 1
 }

so 2 lines need to be modified for the fix to be back-ported. So there is more chances that it will need conflict resolution.

Now another more problematic issue is that if we start with the code like:

for (const i of array) {
   ...
}

Later a new feature change it into:

- for (const i of array) {
+ for (let i of array) {
    ...
 }

And then a fix that need to be back-ported relies on the variable not being a const like:

 for (let i of array) {
    ...
+   i += 1
 }

This back-port will fail (at best when the CI is running).

So this is one of the reason that I think we should reserve the usage of const to real variable that are by design constant (like in Python when we use uppercase). But not inside function/scope just because currently the variable is not reassigned.
And use let in every case where it can be instead of var.

1 Like