Skip to content

Instantly share code, notes, and snippets.

@GregSithole
Last active August 25, 2023 11:57
Show Gist options
  • Save GregSithole/cf2395f71ccc84a3b2e2134a4bc90cf6 to your computer and use it in GitHub Desktop.
Save GregSithole/cf2395f71ccc84a3b2e2134a4bc90cf6 to your computer and use it in GitHub Desktop.
Fizz Buzz Simple Challenge Javascript
/**
* Returns the Fizz Buzz value for a given number.
*
* @param {number} num - The input number.
* @returns {string|number} The Fizz Buzz value:
* - "Fizz" if the number is divisible by 3.
* - "Buzz" if the number is divisible by 5.
* - "FizzBuzz" if the number is divisible by both 3 and 5.
* - The input number if none of the above conditions are met.
*/
function fizzBuzz(n) {
// Added number validation to ensure a number was passed in
if (typeof n !== "number") {
throw new Error("Input must be a valid number.");
}
let result = [];
for (i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
result.push('FizzBuzz');
} else if (i % 3 === 0) {
result.push('Fizz');
} else if (i % 5 === 0) {
result.push('Buzz');
} else {
result.push(i);
}
}
return result.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment