I want to ask as to why when I turn if (i % 3 === 0 && i % 5 === 0) {console.log("Fizz")}; into else if(i % 3 === 0 && i % 5 === 0) {console.log("Fizz")}; vice versa, I only get Fizz and Buzz on console.log and no FizzBuzz unlike when I used if. I expect the same result with else if thus I think they should be the same?
Below is the full script for reference.
let answer = 100;
for (let i = 1; i <= answer; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
}
forget them oldskool solutions.
IMHO the most important Array Method to learn is Map:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Which "walks over" the Array and returns a new value for that Array index
let arr = Array(100)
.fill((x, div, label) => x % div ? "" : label) //store Function in every index
.map((func, idx) =>
func(++idx, 3, "Fizz") + func(idx, 5, "Buzz") || idx
);
document.body.append(arr.join(", "));
fill takes a single Object, it is not executed 100 times!
Since JavaScript Functions are Objects this code declares a function once for every index
Note the ++idx because we want to start at 1, not 0
In JavaScript ""+"" is a Falsy value, thus it returns the idx value for non-FizzBuzz numbers
More Array Methods explained: https://array-methods.github.io
When you use else if the previous if condition has to be false for the else if condition to be verified (and its content possibly executed).
Otherwise it's only a chain of indepent ifs.
You don't need to consider the "both case" separately, as your code does. In pseudocode:
if (i is divisible by 3) {
print "Fizz"
}
if (i is divisible by 5) {
print "Buzz"
}
If you run through this on paper, you can see that it will print "FizzBuzz" by executing both conditions. So it is not wrong to have a special case for both, but it is easier (and clearer) to do it without that.