0

I'm trying to run the FizzBuzz problem solving, it seems to be working, however when it reaches the user input number it returns undefined.

Here is my code:

const prompt = require("prompt-sync")();

let userChoice = parseInt(prompt("Please enter a number: "));

function fizzBuzz () {
    for (let i=1 ; i <= userChoice; i++){
        if (i % 3 === 0 && i % 5 ===0) {
            console.log("FizzBuzz");
        }
        else if (i % 3 === 0){
            console.log("Fizz"); 
        }
        else if (i % 5 === 0){
            console.log("Buzz");
        }
        else {
            console.log(i); 
        }
    }
}

console.log(fizzBuzz(userChoice)); 

This is the outcome in the console :
This is the outcome in the console

Dharman
  • 30,962
  • 25
  • 85
  • 135
Diana C
  • 11
  • 1
  • 4
    You're not returning anything from `fizzBuzz()`. – BenM Aug 16 '21 at 19:16
  • 1
    https://stackoverflow.com/q/21020608/3001761 – jonrsharpe Aug 16 '21 at 19:17
  • Remove the `console.log` from the last line. `fizzBuzz` is taking care of logging things along the way. It doesn't return anything to be output. Just call `fizzzBuzz(userChoice);` – StriplingWarrior Aug 16 '21 at 19:20
  • You're trying to pass a parameter into the fizzBuzz function (`fizzBuzz(userChoice)`) but your function doesn't accept a parameter (`function fizzBuzz ()`) – James Aug 16 '21 at 19:23
  • @James `let` is block-scoped, so `userChoice` is still accessible within the function, but yeah, good idea to add it to the param list for `fizzBuzz()`. – BenM Aug 16 '21 at 19:29
  • Hi all, thanks for the help, So I removed the console.log and called the function at the end, it seems to be working now, AdditionalI tried Ben first code option and it wont run at all, sadly – Diana C Aug 16 '21 at 19:35

1 Answers1

1

You need to actually return a value from your fizzBuzz() function. At the moment, that function is returning nothing, so when you log its return value, you're getting undefined.

function fizzBuzz (userChoice) {
    let output = [ ];

    for (let i=1 ; i <= userChoice; i++){
        if (i % 3 === 0 && i % 5 ===0) {
            output.push("FizzBuzz");
        }
        else if (i % 3 === 0){
            output.push("Fizz"); 
        }
        else if (i % 5 === 0){
            output.push("Buzz");
        }
        else {
            output.push(i);
        }
    }

    return output.join("\n");
}

Alternatively, just don't wrap your actual function call in a console.log, so your last line will simply be:

fizzBuzz(userChoice);
BenM
  • 52,573
  • 26
  • 113
  • 168