What is the role of += when concatenating two strings? (Eloquent JS FizzBuzz)

390 Views Asked by At
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);
}

Can someone explain how the += operator preceeding "Fizz" and "Buzz" plays a role in the concatentation of FizzBuzz when numbers are divisible by both 3 and 5?

My initial code was the following, which produced the same result:

 for (var number = 1; number <= 100; number++) 

 if (number % 3 == 0 && number % 5 == 0) {
    number == console.log("FizzBuzz");
 }

 else if (number % 3 == 0) {
    number == console.log("Fizz");
 }

 else if (number % 5 == 0) {
    number == console.log("Buzz");
 }

 else {
    console.log(number);
 }
2

There are 2 best solutions below

2
On BEST ANSWER
output += "Fizz";

is just the shorthand version of

output = output + "Fizz";

It will concatenate the value in output with Fizz, create a new string and store it back in output.

The important thing is, it creates a new String object, because String objects are immutable.

As per the logic, if the number is divisible by 3, then output will become Fizz, since it is already empty. And if the number is also divisible by 5, the output will become FizzBuzz (Fizz + Buzz).

0
On
output += "Fizz";

is shorthand for

output = output + "Fizz";

Keeping a variable output allows for the case where both "Fizz" and "Buzz" are applicable to the number in the loop iteration and need to be combined. output gets reset every loop.