This recommendation seems short sighted to me. The let-in-loop structure is precisely the type of thing that browser developers optimize in their JS engines.
An historical example of this is the for (var i = 0, j = a.length; i < j; i++) { ... } pattern. The idea was that repeated property look-up is slower than assignment. Once upon a time that was true, but the for (let i = 0; i < a.length; i++} ... pattern is optimized today; there’s near-zero performance difference between the two patterns in modern web browsers.
Besides, your “good” version may be worse for performance. I know that JS engines can optimize your “bad” example in the following way:
while (i--) {
/** optimized out: let name = ... **/
console.log(new Array(i + 1).join('bob ') + 'marley');
}Here, the JS interpreter knows that name isn’t used outside of the while-block (because it can’t be!), and it can inline the variable name directly in the console.log expression.
That’s not possible in your “good” example because you’re mutating a closure. It may not be possible for the JS interpreter to tell if name is reused elsewhere, so the variable substitution optimization may not be considered.
As always, I’d caution against premature optimizations. Unless you have data that the let declaration inside a loop is causing a performance issue, it’s much more important to clearly communicate your intentions to other developers (and your future self) than to worry about what the interpreter may or may not be doing.
