DEV Community

Nitin Sijwali
Nitin Sijwali

Posted on • Updated on

FizzBuzz program in javascript

In javascript interviews, the most frequently asked question is "FizzBuzz." The goal of asking this question is to see how you approach solving the problem rather than the solution itself.

The following is an example of a question. Print the numbers 1 to 100 that meet the following conditions:

  • Print "Fizz" if a number is divisible by 3.
  • Print "Buzz" if a number is divisible by 5.
  • Print "FizzBuzz" if the number is divisible by both 3 and 5.
  • else print the number itself.

The solution is straightforward, but the approach is critical.

A newcomer would do it like this:

function fizzBuzz(){
   for(let i = 1; i <= 100; 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);
     }
   }
}
Enter fullscreen mode Exit fullscreen mode

This is how people with some experience would do it:

 function fizzBuzz(){
   for(let i = 1; i <= 100; i++){
// instead of checking if divisible by both 3 and 5 check with 15.
     if(i % 15 === 0){ 
        console.log('FizzBuzz');
     }else if(i % 3 === 0){
        console.log('Fizz');
     }else if(i % 5 === 0){
        console.log('Buzz');
     }else{
        console.log(i);
     }
   }
}

fizzBuzz()
Enter fullscreen mode Exit fullscreen mode

However, a pro developer🚀 would do it as follows:

function fizzBuzz() {
 for(let i = 1; i <= 100; i++){
  console.log(((i%3  === 0 ?  "fizz": '') + (i% 5 === 0 ? "buzz" : ''))|| i)
 }
}
fizzBuzz()
Enter fullscreen mode Exit fullscreen mode

I hope this helps you guys solve it like a pro. Any additional pro solutions are welcome.

Please ❤️ it and share it your with friends or colleagues. Spread the knowledge.


Thats all for now. Keep learning and have faith in Javascript❤️

Top comments (3)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

hmmm:

[...Array(100)].map((_,i=i+1)=>(console.log(
    i++ && !(i%15)?'FizzBuzz':!(i%5)?'Buzz':
    !(i%3)?'Fizz':i)))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nsijwali profile image
Nitin Sijwali

🔥

Collapse
 
nsijwali profile image
Nitin Sijwali

That's amazing