Codecademy FizzBuzz app, stuck on step 1

mrdavidjcole picture mrdavidjcole · Jan 10, 2012 · Viewed 8.9k times · Source

Here's my code for Codecamedy's FizzBuzz lesson

var i;
for ( i = 1; i > 20; i++ ) {
  "hello"
  if ( i % 3 === 0 ) {
    if ( i % 5 === 0 ) {
      "FizzBuzz";
    }
    else {
      "Fizz";
    }
  }
  else if ( i % 5 === 0 ) {
    "Buzz";
  }
 else {
    i;
  }
}

I'm trying to first test whether or not the number (i) is divisible by 3. If it is, I then want to check whether it is also divisible by 5. If both conditions are true, I want it to say "FizzBuzz". If only the first condition is true, it should say "Fizz". Then, after determining that i is not divisible by 3, it should check whether i is divisible by 5 and show "Buzz" if that's the case. Failing all divisibility, it should just show the number.

As I expected... it doesn't work as expected. What terribly embarrassing mistakes have I made?

Answer

Adam Rackis picture Adam Rackis · Jan 10, 2012

First, your loop is not even getting off the ground:

for ( i = 1; i > 20; i++ )

will not iterate even once since the middle condition is initially false. I think you meant:

for ( i = 1; i <= 20; i++ )

"FizzBuzz";

is just a string literal that JavaScript is ignoring. You need to output this string somehow:

console.log("FizzBuzz");

Also, this block

else {
    i;
  }

is also not doing anything. Did you want to display numbers that were divisible by neither 3 nor 5?

else {
    console.log(i);
  }

And, on a similar note, what is the "hello" at the top loop supposed to do?


On a more positive note, I see you're using strict equality:

if ( i % 5 === 0 )

this is a very, very good habit to be in. The non-strict equality operator == will do all sorts of implicit conversions if you're not careful. Always use strict equality unless you purposefully want these implicit conversions to happen.