It's Study Time

Fizz Buzz program in JavaScript

Fizz Buzz is one of the simplest but frequestly asked program in all laguage interviews.

The question goes like below.
-Write a program that prints the numbers from 1 to n. While printing the number if the number is divisible by 3 print ‘Fizz’ and when the number is divisible by 5 print ‘Buzz’. When the number is divisible by both 3 & 5 it should print FizzBuzz.

Lets write the program in JavaScript

//The simplest form which is self explanatory
for (let i = 1; i <= 20; i++) {
    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);
    }
}
//Lets make it little shorter. Now the program is like below

for (let i = 0; i < 100; ) {
    let isFizz = ++i % 3 ? '' : 'Fizz';
    let isBuzz = i % 5 ? '' : 'buzz';

    console.log(isFizz + isBuzz || i);
}

This can be written in shorter form like below

for (let i = 0; i < 100; ) { console.log((++i % 3 ? '' : 'Fizz')+ 
(i % 5 ? '' : 'buzz') || i); }

Share this post

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email
×

WhatsApp Chat

×