1

I'm creating a simple Javascript Function that should write the numbers from 1 to n. For any multiplier of 3, it outputs "Fizz", instead of multiplers of 5 you output "Buzz", and if they happen at the same time, you should use "FizzBuzz". The output of the function should be a mixed array of numbers and strings.

My current code is outputting the array order and expected values incorrectly.

function fizzbuzz (n) {
  let arr = [];
  
    for (let i = 0; i < n; i++){
      //if i is a multiple of 3 then Fizz
      if(i % 3 === 0) {
        arr.push("Fizz");
      }
      //if i is a multiple of 5 then Buz
      if(i % 5 == 0) {
        arr.push("Buzz");
      }
      //if both then FizzBuzz
      if(i % 3 === 0 && i % 5 === 0) {
        arr.push("FizzBuzz");
      }
      else {
        arr.push(i);
      }
    }
  return arr;
}

When fizzbuzz(7) is entered, I expect the output to look like this:

[0, 1, 2, "Fizz", 4, "Buzz", "Fizz", 7];

Instead, it's this:

["Fizz","Buzz","FizzBuzz",1,2,"Fizz",3,4,"Buzz",5,"Fizz",6]

Could someone enlighten me to the fault in my logic? This should be more straightforward than I had originally thought.

solo1999
  • 31
  • 3
  • 2
    You should use else if instead of just ifs following each other because if it's both a multiplier of 3 and 5, all 3 first conditions are true and are gonna be executed – Emilien Dec 30 '22 at 17:20

1 Answers1

2

You have three different if statements there, the last one having an else clause, instead of one continuous if statement with several else if clauses. Note that for this to work properly you need to first test the "FizzBuzz" condition:

function fizzbuzz (n) {
  let arr = [];
  
    for (let i = 0; i < n; i++){
      //if both then FizzBuzz
      if(i % 3 === 0 && i % 5 === 0) {
        arr.push("FizzBuzz");
      }
      //if i is a multiple of 3 then Fizz
      else if(i % 3 === 0) { // Changed to an else-if
        arr.push("Fizz");
      }
      //if i is a multiple of 5 then Buz
      else if(i % 5 == 0) { // Changed to an else-if
        arr.push("Buzz");
      }
      else {
        arr.push(i);
      }
    }
  return arr;
}

Quick note regarding the expected output - 0 is divisible by 3 and 5 (and other other integer, for that matter), so the first element of the array should be "FizzBuzz"

Mureinik
  • 297,002
  • 52
  • 306
  • 350