1

I am trying to understand the difference between these two ways of writing the loop. the resulting for both code snippets is different . Why?

  1. for loop : output variable is inside the loop , gives different result.

    for (var n = 1; n <= 100; n++) {
      var output = "";
      if ( n % 3 == 0)
        output += "Fizz";
      if (n % 5 == 0)
        output += "Buzz";
      console.log(output || n);
    }
    
  2. for loop : output variable is outside the loop , gives different result.

    var output = "";
    for (var n = 1; n <= 100; n++) {
      if ( n % 3 == 0)
        output += "Fizz";
      if (n % 5 == 0)
        output += "Buzz";
      console.log(output || n);
    }
    
K. Kaur
  • 59
  • 1
  • 1
  • 7
  • 3
    1. If you have different results you should clarify them. 2. In the first case `output` is re-initialized to an empty string at every iteration – UnholySheep Oct 05 '16 at 18:47
  • 1
    This isn't really about scope as much as it is about the initialization. – Pointy Oct 05 '16 at 18:48
  • 1
    Variable declarations like `var output` are hoisted to the top. Assignments like `output = ""` are not. – Oriol Oct 05 '16 at 18:51
  • 1
    you really want to *undersand* the difference? Then unroll the loop (manually), at least 3-4 iterations worth. That should show you the difference. – Thomas Oct 05 '16 at 19:26

1 Answers1

1

In both cases, the declaration of output is treated as if it were outside the loop. What's important, however, is the initialization of output:

  var output = "";

sets the variable to the empty string (""). If you put the initialization inside the loop, then the variable's value is cleared at the start of each iteration. That wipes out all the work that the previous iteration tried to do.

So, assuming your code appears in some function, the first example would be interpreted as if it were written:

function whatever() {
  var output;
  // ...
  for (var n = 1; n <= 100; n++) {
    output = "";
    if ( n % 3 == 0)
      output += "Fizz";
    if (n % 5 == 0)
      output += "Buzz";
    console.log(output || n);
  }
  // ...
}

Clearly, setting the variable back to "" at the start of each iteration defeats the whole point of the loop.

Pointy
  • 405,095
  • 59
  • 585
  • 614