In this article, we look at FizzBuzz, a very common programming task in software development interviews. Since the solution utilizes a few major concepts, this task has become a go-to for interviewers.
If you are new to the concept, I’d recommend you follow step by step to understand the concept as a whole. However, If you are here to refresh your knowledge, you can jump straight to the solutions.
What is FizzBuzz?
Firstly, let’s get this out of the way, FizzBuzz is a task where the programmer is asked to print numbers from 1 to 100, but here’s the catch, multiple of three should print “Fizz” and similarly print “Buzz” for multiples of 5 and lastly print “FizzBuzz” for multiples of three and five.
Although the last may seem straightforward, even seasoned programmers tend to get the logic wrong at times.
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
**
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function(n) {
let answer = [];
for(let i = 1; i <= n ; i++){
if(i % 15 === 0){
answer[i] = "FizzBuzz"
continue
}
else if(i % 3 ===0 ){
answer[i] = "Fizz"
continue
}
else if(i % 5 === 0){
answer[i] = "Buzz"
continue
}
else{
answer[i] = `${i}`
continue
}
}
answer.shift();
return answer;
};
Top comments (2)
Hi Falade,
Please accept my comments as constructive and in the interest of giving your readers the best possible information. First, can I suggest you might want to use the fenced code block syntax in your future posts (with the javascript keyword) to get syntax colouring, as shown below.
Whilst the solution you provide above works correctly, as someone usually the other side of the technical interview table, I would like to point out a few things.
function fizzBuzz(n) {
but it is not wrong, just a little odd.continue
keywords do nothing as you have useelse
to guard later conditions, so they can be removed without impacting the functionality.answer.shift()
call also does nothing and can be removed.answer[i]
to add a value to the answers array is also a little unconventional when the Array.push method is available.The result would be something like:
To take this one step further, we can remove the
if...else
altogether using the ternary operator. This way when i = 15 we still get FizzBuzz, also when not Fizz or Buzz, the value of i is still added to the array as a string.In the above example you will see I used the
console.table
call to execute the function and present the results.Keep posting, keep learning (I am), regards, Tracy
Another one, allowing you to change 'Fizz' and 'Buzz' if you like:
😛