0

This is my code

function test(number) {
    if (number % 15 == 0) {
        return "FizzBuzz";
    }

    if (number % 3 == 0) {
        return "Fizz";
    }

    if (number % 5 == 0) {
        return "Buzz";
    }

    return number.toString();
}

I type test(15).

result print "FizzBuzz"

Why doesn't it print "FizzBuzz" "Fizz" and "Buzz" ?

7
  • 1
    because it fulfills one condition and returns -- it doesn't make it to the other conditions. Commented Apr 26, 2017 at 14:29
  • 1
    because return breaks out of the function Commented Apr 26, 2017 at 14:29
  • because of the return which means: at this point jump out of function and return the specific value Commented Apr 26, 2017 at 14:29
  • 3
    This is why fizzbuzz exists... Commented Apr 26, 2017 at 14:30
  • 1
    I dont see any else in the code Commented Apr 26, 2017 at 14:35

5 Answers 5

2

You can only return once per function. After return it goes back to the line were you called the function.

Sign up to request clarification or add additional context in comments.

Comments

1

When you return, the fuction is terminated and the passed value is returned. Any code that follows the return is not executed.

In your case, the function enters the first statement (as the number % 15 == 0 statement returns true), sees a return, returns FizzBuzz, and breaks out of the function.

Comments

0

Because you leave the function with a return write this instead

function test(number) {
        var res = "";
        if(number % 15 == 0){
            res += "FizzBuzz";
        }
        if(number % 3 == 0){
            res += "Fizz";
        }
        if(number % 5 ==0){
            res += "Buzz";
        }
        return res;
}

It will add the results from the conditions.

Comments

0

@Yehuda correctly explained why it only display FizzBuzz: The execution of a function is stopped when you return.

Here is one of the (many) solutions to get all the modulos: It defines an array which in you can store the modulos. At the end of the code, it returns the array.

function test(number) {
    var res = [];
    if(number % 15 == 0) {
        res.push("FizzBuzz");
    }
    if(number % 3 == 0) {
        res.push("Fizz");
    }
    if(number % 5 == 0) {
        res.push("Buzz");
    }
    console.log(res);
    return res;
}
test(15);

Comments

0

If you want to return varius:

function test(number) {
        res = '';
        if(number % 15 == 0){
            res +=   " FizzBuzz";
        }
        if(number % 3 == 0){
            res +=   " Fizz";
        }
        if(number % 5 ==0){
            res +=  " Buzz";
        }
        return number + " - "  + res.toString();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.