Introduction to Objects I


#1

for(i=1;i<=20;i++){
if(i%3===0){
console.log(“Fizz”)}
else if(i%5===0){
console.log(“Buzz”)}
else if((i%5===0) && (i%3===0)){
console.log(“FizzBuzz”)}
else {
console.log(i)}
}

hi ,what is wrong with it ?
show : Oops, try again. You printed Fizz when you should have printed FizzBuzz


#2

Currently, the

console.log(“FizzBuzz”)
is unreachable. Try changing the order of your if statements.

#3

yes ,i can reach it @vjhawkins
but could you me why the order must be changed ?
i donot know why ?

for(i=1;i<=20;i++){
if((i%5===0)&&(i%3===0)){
console.log(“FizzBuzz”)}
else if (i%3===0){
console.log(“Fizz”)}
else if(i%5===0){
console.log(“Buzz”)}
else {
console.log(i)}
}


#4

Somehow, you got it right. I think you know more than you think you know.

With if…else if…else statements, only the first condition that is true is ran.

Consider the following code as a simplified example:

var x = 3;
if(x < 5)
     console.log("Smaller than 5");  // This prints but we want the smallest number to print
else if (x < 4)
     console.log("Smaller than 4");
else if (x < 3)
     console.log("Smaller than 3");
else if (x < 2)
     console.log("Smaller than 2");
else
    console.log("Round to 10");

More than one of the statements are true, but since the very first if

if(x<5)
condition is true, the second if
else if (x < 4)
condition is never evaluated. Also, the
 else if (x < 3) 
or
else if (x < 2)
or
else
are not evaluated either.

If you wanted them all to evaluate properly, you have to order them in a way that would allow them to, such as:

var x = 3;

if(x < 2)
   console.log("Smaller than 2");
if(x < 3)
   console.log("Smaller than 3");
if(x < 4)
   console.log("Smaller than 4"); // This correctly prints
if(x < 5)
   console.log("Smaller than 5");
else
   console.log("Round to 10");

#5

thanks for your explanation!


#6

This topic was automatically closed after 7 days. New replies are no longer allowed.