4. I have to celebrate your baby


#1


4. I have to celebrate your baby


I have successfully finished the exercise but only with help from someone, but that person did not explain to me something: I was having problem with this part: i%3===0, in order to check if the number is divisible by 3 I was simply doingi%3, can anyone please explain to me why i must use ===0 ? Thank you very much for your time and help!


var numbers = function(){
    for (i=1; i<=20; i++){
        if(i%3===0 || i%5===0){
            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)
            }
    }
}
numbers();


#2

At first you dont need
if(i%3===0 || i%5===0){

i cant find any reason to use this.simply you can do

var numbers = function(){
    for (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)
            }
    }
}
numbers();

now i coming to your question

The modular operator (%) returns the division remainder.
for example

12 % 5 // 2
5 % 2 // 1
6 % 3 // 0

so if the number divisible by 3 it''ll be 0 .so we are cheking whether the division remainder 0 or not.
but if you do just

else if (i%3){
  console.log('Fizz')
 }

it means
else if(true) so it'll not go to the next codition.it'll print continuously Fizz

i hope you've understand now :slight_smile:


#3

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