1

For example in this code:

... snip    
      breadthFirst (callback) {
        // let node; // here?
        while (this.queue.length > 0) {
          // let node = this.queue.shift(); // or here?
          callback(node);
          node.childNodes.forEach( (node) => {
            this.queue.push(node);
          });
        }
      }
    }
... snip

I could have declared let just outside the while loop or inside the while loop. I'm not sure which is better.

Note that I am using let which has block scope so this previous SO question is not relevant.

  • Limit the scope of your variable, therefore declare it inside the while to save on memory, as long as the variable is not needed outside the while loop – cela May 02 '18 at 18:30
  • Can you verify w/ documentation that it is not "re-declared" on each loop iteration? –  May 02 '18 at 18:37
  • @user9723590 variable declaration is a syntactic construct. It makes no sense to ask whether it cab be redeclared at runtime. – OrangeDog Jun 17 '19 at 12:03

2 Answers2

1

You generally want to limit the scope of variables as much as possible, as it's a waste of memory to establish variables outside of all scope where they're needed/used.

So I would say the latter is better, inside the while loop, as long as you don't need it again after the while loop.

Sam
  • 705
  • 1
  • 9
  • 18
  • 1
    Can you verify w/ documentation that it is not "re-declared" on each loop iteration? –  May 02 '18 at 18:37
  • @MikeZuckerman Declarations are processed at compile time, not during execution. – Barmar May 02 '18 at 18:53
  • What I find perplexing then is that it is declared a const. If there is only one variable processed at compile time ... it must change for each loop iteration, how then can a const work? –  May 18 '18 at 16:41
0

If you don't mind a third option, I'd say neither. You're already using modern syntax, so why not use modern iteration constructs, like for-of? This lets you more cleanly declare it in the head of the loop.

breadthFirst (callback) {
  for (const node of this.queue) {
    callback(node);
    this.queue.push(...node.childNodes);
  }
  this.queue.length = 0;
}

This also removed the inner loop by taking advantage of spread syntax with the variadic .push() method.

As to whether or not the variable is "redclared" (I assume you're worried about repeatedly creating a new scope), this is going to come down to implementation detail more than documentation.

The const node is indeed a per-iteration variable, so that it can be useful for functions declared in the loop, but that doesn't prevent optimizations where the variable would be pre-declared and shared by all iterations in situations like this where there are no closure issues.