How to make FizzBuzz in JavaScript

How to make FizzBuzz in JavaScript

In this tutorial we will talk about simple FizzBuzz. We will write a simple application that prints integer from 1 till 100. When it multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. For numbers which are multiples of both 3 and 5 print “FizzBuzz”. More about FizzBuzz.

Okay, first of all let’s start with simple for loop  statement. The for statement has 3 main parts: where to start, where to stop, and how much to change each time.

// for (start; stop; how much to change each time)
for (var counter = 3; counter <= 5; counter = counter + 1) {
    console.log(counter);
}

So it start at 3, stop at 5 and add +1 each time and it gives you an output:

3
4
5

 

Next step will be understanding the condition statement

if (this condition is true) {
    // do this part of code
} else {
    // do this instead
}

 

Example:

if ( 2 > 1) {
    console.log("Time2Code!");
} else {
    console.log("Hi there!")
}

And the output will be like this:

Time2Code!

 

So let’s imagine we need to help Formula 1 to count down. Let’s use for loop for that kind of job to help Formula 1 start their competition. Here you can see a good example of

for (i=10; i>=0; i--) {
if (i===0){
	console.log("Start!"); 
} else {
    console.log(i);
	}
}

With the output:

10
9
8
7
6
5
4
3
2
1
Start!

I think you can understand the art of loops now and we are ready to go to the next step.

Now we will make for loop:

for (i=1; i<=100; i++) {
	console.log(i);
}

Time to add % modulus (division remainder, example: x=y%2). More about JavaScript arithmetic operations.  In addition try to remember that you’re checking equality of two things and you need to use “===", not “=".

Fizz:

for (i=1; i<=100; i++) {
if (i%3 === 0){
    console.log("Fizz");
} else {
    console.log(i); 
	}
}

Buzz:

for (i=1; i<=100; i++) {
if (i%3===0){
	console.log("Fizz");
} else if (i%5===0) {
	console.log("Buzz");
} else {
	console.log(i); 
	}
}

FizzBuzz:

for(i=1;i<=100;i++) {
if (i%15===0) {
	console.log("FizzBuzz");
} else if(i%5===0) {
	console.log("Buzz");
} else if(i%3===0) {
	console.log("Fizz");
} else {
	console.log(i);
	}
}

Now we have working FizzBuzz application.

Leave a Reply

Current ye@r *