I prefer using let and const rather than var. As to when to use let vs const, it depends on what happens to your variables within the block structure of your code. For example, taking this code:
var bob = 0;
if (thing) {
bob = 10;
} else {
bob = 20;
}
console.log(bob);
the obvious refactor with let is:
let bob = 0;
if (thing) {
bob = 10;
} else {
bob = 20;
}
console.log(bob);
Trying this with const would not work, because we are changing the value of bob. Trying to move the const into the if also fails, because let and const are block scoped.
const bob = 0;
if (thing) {
const bob = 10; // not the same bob as the above bob
} else {
const bob = 20; // not the same bob as either of the above bobs
}
console.log(bob); // always logs 0
However, you can use const quite flexibly with objects:
const obj = { a:1, b:2 };
obj.c = 3; // allowed - we aren't changing the definition of obj as an object.
obj = 'Bob'; // not allowed
I’ve found that the easiest way to work out what to use is to configure eslint into your editor. It tells you exactly which to use based on the structure of your code .