Title photo
frugal technology, simple living and guerrilla large-appliance repair
Wed, 29 Mar 2017

Eloquent JavaScript - Chapter 2 exercises - Fizz Buzz

I'm not saying I will make it through all 22 chapters of "Eloquent JavaScript," by Marijn Haverbeke, but enough people I respect have recommended the book that I'm doing my best to absorb what I can from it.

To that end, I am doing the exercises in the back of each chapter, and I plan on presenting my solutions here.

This entry also serves as a test of the Highlight.js JavaScript library, which I just added to this Ode site for syntax highlighting of code. I'm using the zenburn CSS.

Back to "Eloquent JavaScript." If you don't want any hints, don't go past the blog index. I will only start showing my code after the "read more" portion of each entry.

Before maybe a year ago, I'd never heard of Fizz Buzz, where you write a program that outputs the words Fizz, Buzz or Fizz Buzz depending on whether a number is divisible by 3, by 5 (and not 3) or by 5 and 3.

Fizz Buzz is supposedly used as a programming test in hiring. I was surprised when it was given as the second exercise in Chapter 2

Here is my solution:

/* Eloquent Javascript
Chapter 2
Fizz Buzz exercise

Solution by Steven Rosenberg, Feb. 6, 2017

Write a program that uses console.log to print all the numbers
from 1 to 100 with two exceptions:

For numbers divisible by 3, print "Fizz" instead of the number

For numbers divisible by 5 (and not 3), print "Buzz" instead of the number

Then, for numbers divisible by 5 and 3, print "FizzBuzz"

*/

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

It's a traditional for loop with a series of if/else if/else conditions to print the proper words as determined by using the remainder/modulus operator %.

My C++ class at LA Valley College prepared me well for this kind of problem, so it was a matter of placing the statements in the proper order, with the most restrictive condition (Fizz Buzz) coming before the less restrictive Fizz and Buzz.

I used === even though == would have sufficed.