And the good - what's the difference?


#1

I am hoping someone might be able to explain to me why my original code did not work (I have it commented out). The code that did ultimately work is under my commented out code. Why did the ' / ' operator and " true" statement not work in my code but the ' % ' operator and ' 0 ' statement did in the code that ultimately worked?

https://www.codecademy.com/en/courses/spencer-sandbox/0/3?curriculum_id=506324b3a7dffd00020bf661#

Oops, try again. You printed 3 when you should have printed Fizz.


/*
 for(var i = 1; i <= 20; i++) {

    if(i / 3 === true && i / 5 === true) {
        console.log("FizzBuzz");
       
    }
    
    else if(i / 3 === true) {
        console.log("Fizz");
       
    }
    
    else if(i / 5 === true) {
        console.log("Buzz");
     
    }  
  
    
    else {
        console.log(i);
    }
 }
 */
 
 
 for(var i = 1; i <= 20; 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);
    }
 }


#2

This happens because (integer/3) will give an integer. For example, 8/3 = 2. And in programming languages, anything else than 0 is true.

So the first two cases will run fine because 1/3 and 2/3, both end up being 0. Hence it will print the else part. But after that, every case for 3 will be true.


#3

That makes sense. What about the % operator? Doesn't that give a remainder/also not equal zero? Guess I'm not totally proficient in my understanding of the difference between the ' / ' operator and the ' % ' operator. I understand that they both divide but it gets blurry for me after that.


#4

Yes, % operator returns the remainder. But when checking with % operator, we check if x % y === 0 or not, not true or false. For example:

if ( 13 % 3 === 0) [13 % 3 will return 1. 1 will be compared to 0 and condition will evaluate as false. Hence, the if portion will not run.]

if (13 / 3 === true) [Though 13 is not divisible by 3, the 13/3 operation will return 4. So the statement becomes if (4 === true), which is actually true! Hence, the condition becomes true and the if loop runs when it shouldn't have.]


#5

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