So the time will come when there will be basically no point at all of using the var keyword anymore for the same reasons why it no longer makes sense to go out of ones way to make sure that there code will not break in Internet explorer 5. It is all about looking at the browser vendor and version data of a sites analytics, and when I do so it looks like most people are using modern evergreen browsers these days. So if it has not happened for you yet it is only a matter of time until it is just a question of using let, const, or both. If you do want to just use only one, like the good old days of var only, then the choice is clear, the choice is let, so lets get into why that is.
This code results in an error, but not just because the value of n is lower than 42. If I where to replace all instances of let with var the value undefined will be logged rather than the error message ‘a is not defined’ because of the variable hoisting aspect of the var keyword.
In addition even if I where to increase the value of n so that the code in the body of the if statement runs, I will still get the same error message. This is of course what is expected as the whole point of using let is to have block level scope, rather than function level scope that var alone can achieve.
One thing that comes up with using let over the traditional var is redeclaring a variable with the let keyword over var. The var keyword is more forgiving with this, allowing for a variable to be redeclared over and over again in the same bit of code. The let keyword on the other hand will throw a nasty error if this is done.
For the most part this is not a big problem for me, as I generally do not do this when writing legacy javaScrip style code. There may be some rare extenuating circumstances in which this might get annoying, but I am sure I could find a way to manage.
One of the draw backs of using var over let is of course not having block level variables scope. When it is just var that is used it is a situation in which there is function level scope only. That being said it is possible to simulate block scope with self executing function expressions however.
It may be ugly, but for the most part the same desired effect is achieved.