mardi 28 avril 2015

using an if statement inside a while loop

I just figured out how to test for certain conditions and modify output within a loop. But I noticed that testing for two conditionals with the && operator only works in an if/else if/else if/else chain if it's the first one tested for.

Can someone explain why this works:

var number = 0;
var counter = 0;

while (counter < 100) {
  number ++;
  counter ++;
  if (number % 3 == 0 && number % 5 == 0)
    console.log ("FizzBuzz");
  else if (number % 3 == 0)
    console.log("Fizz");
  else if (number % 5 == 0)
    console.log("Buzz");
  else
    console.log(number);
}

But this does not?:

var number = 0;
var counter = 0;

while (counter < 100) {
  number ++;
  counter ++;
  if (number % 3 == 0)
    console.log("Fizz");
  else if (number % 5 == 0)
    console.log("Buzz");
  else if (number % 3 == 0 && number % 5 == 0)
    console.log ("FizzBuzz");
  else
    console.log(number);
}

Aucun commentaire:

Enregistrer un commentaire