Fernando Papaqui

fp/dev

FizzBuzz (Solution)

A couple of weeks ago I was reading a great book called Eloquent Javascript which is a great source of knowledge. One of the first exercises is called FizzBuzz and the goal is to:

  • Write a program that prints each number from 1 to 100 on a new line.
  • For each multiple of 3, print “Fizz” instead of the number.
  • For each multiple of 5, print “Buzz” instead of the number.
  • For numbers which are multiples of both 3 and 5, print “FizzBuzz” instead of the number.

At first I felt overwhelmed, I didn’t even try. I just kept reading the book and doing some local testing with loops and so. I read somewhere that this was a job interview question, which at the time seemed a bit too much.

But suddenly, after hours of digging into programming concepts and literature, one day it just came as if it was the most logical thing to think. What if…

My solution

Using: If else

'use strict';

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);
  }
}

Fernando Papaqui

Front end web developer working with Gatsby, JS, React, and WordPress. Mexico native.