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);
}
is just the shorthand version of
It will concatenate the value in
output
withFizz
, create a new string and store it back inoutput
.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
, thenoutput
will becomeFizz
, since it is already empty. And if the number is also divisible by5
, theoutput
will becomeFizzBuzz
(Fizz + Buzz
).