Where to Define Loop Variables - JavaScript


The instructions in the lodash project for making the methods findKey() and chunk() say to define variables within loops. But isn’t it better practice to conserve memory by initializing the variable right before the loop, so that it’s only initialized once instead of each iteration of the loop?

findKey(object, predicate) {
    for (let key in object) {
      let value = object[key];
      let predicateReturnValue = predicate(value);
chunk(array, size) {
    for (let i = 0; i < array.length; i += size) {
      let arrayChunk = array.slice(i, i + size);

When scoping is a concern, the narrower the better. Remember each iteration of a for loop presents with a brand new block, so let and const are still valid, and they don’t have to deal with any variables from outside of that block scope.