Javascript if Statement Question 2 FizzBuzz

FizzBuzz

 P:Write a function called *fizzbuzz* that accepts a single argument n.

fizzbuzz should return "Fizz" if n is a multiple of 3

fizzbuzz should return "Buzz" if n is a multiple of 5

fizzbuzz should return n if n is a multiple of neither 3 nor 5.

 AnswerCode:
 function fizzbuzz(n) {
     //your code
 }
                             
 console.log(fizzbuzz(3));
 console.log(fizzbuzz(5));
 console.log(fizzbuzz(15));
 console.log(fizzbuzz(4));


function fizzbuzz(n) {
    var output = "";
    if (n % 3 === 0) output += "Fizz";
    if (n % 5 === 0) output += "Buzz";
    return (output ? output : n); 
}

// Output
console.log(fizzbuzz(3));
// => "Fizz"

console.log(fizzbuzz(5));
// => "Buzz"

console.log(fizzbuzz(15));
// => "FizzBuzz"

console.log(fizzbuzz(4));
// => "4"



PreviousNext

Related