FizzBuzz program in javascript
Nitin Sijwali

Nitin Sijwali @nsijwali

About: Surgeon who gives the HTML skeleton javascript soul and CSS clothes

Location:
Delhi, India
Joined:
May 12, 2022

FizzBuzz program in javascript

Publish Date: May 16 '22
2 4

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❤️

Comments 4 total

  • Frank Wisniewski
    Frank WisniewskiMay 16, 2022

    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
  • Nitin Sijwali
    Nitin SijwaliMay 16, 2022

    That's amazing

Add comment