-3

The code is below -

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

If I do not have let output = "" the code will not run. Why is that statement required?

Tommy
  • 21
  • 1
  • 7
  • 2
    I think because you need the variable declared before you can assign to it – Abdul Ahmad Jan 22 '19 at 19:18
  • 3
    Well if you don't declare the variable `output`, the statement `output += "…"` that tries to use it will throw an exception. Your [developer tools](https://webmasters.stackexchange.com/q/8525) should show you this error. – Bergi Jan 22 '19 at 19:18
  • 1
    This will not work as you expect, you need to put `output` outside of the loop. Also, you can just run it without output defined and read the error. – Ibu Jan 22 '19 at 19:19
  • The code runs now and outputs fizz, buzz, and fizzbuzz while the loop runs. I just don't understand the need for the output variable. – Tommy Jan 22 '19 at 19:20
  • 1
    @lbu Actually the code currently does work just fine. Notice that the `console.log` is inside the loop as well. – Bergi Jan 22 '19 at 19:20
  • @TommyLonergan Well you hardly can do it without if you don't want to repeat `console.log` statements – Bergi Jan 22 '19 at 19:21
  • What does this have to do with scope? It doesn't matter if `output` is defined inside or outside the loop, the matter is that it needs to be defined. It seems OP doesn't understand the need for defining the variable before concatenating – MC10 Jan 22 '19 at 19:25

2 Answers2

0

It is because you have written output +="Fuzz" which means output = output +"Fizz". If you didn't initialize the output code will not understand what to took for output(right after=) and give you error. You can initialize the output (let) before loop.

Rajesh
  • 59
  • 7
0

because without let output="" the variable output is undefined, so your code will crash with the error output is not defined

Mike
  • 555
  • 3
  • 14
  • why do I define output as a space though "" – Tommy Jan 22 '19 at 19:57
  • you aren't defining it as a space, you're defining it as an empty string. You'd type `let output = " "` if you wanted to set it to a space. the reason you initialize it to an empty string, as opposed to, say just putting `let output` is because if you don't assign a value to your variable it is simply `undefined`. if you then append a string to your undefined variable with `output += fizz`, you will now have a string that reads `undefinedfizz` – Mike Jan 23 '19 at 20:14