+ 2

Javascript

I need help please, i started my javascript career with Eloquent Javascript and bumped into this problem. I was asked in an exercise to write a loop that displays numbers from 1 - 100 in the console. now, i was asked to replace that were divisible by 3 with "Fizz" and those divisible by 5 with "Buzz" So i wrote this code: <script type="text/javascript"> for(var num=1; num <= 100; num++){ if (num % 3 ==0) { console.log= "fizz"; } if (num % 5 ==0) { console.log= "buzz"; } console.log(num); } and got it wrong. Now this was the solution: <script type="text/javascript"> for(var num=1; num <= 100; num++){ var output=""; if (num % 3 ==0) { output += "fizz"; } if (num % 5 ==0) { output += "buzz"; } console.log(output || num); } But a dont understand why they had to create a variable with an empty string and the rest of the flow with that output variable confuses me. I need your help please.

27th Jul 2017, 6:06 PM
Peter Claver
Peter Claver - avatar
5 Réponses
+ 4
Your task was to replace the numbers divisible by 3 or 5. You didn't replace the numbers, you just added "buzz" and "fizz" to these numbers. The empty output string is required to test, if this variable is set. If it isn't, then the number is printed. -> console.log(output || num)
27th Jul 2017, 6:16 PM
PitF
PitF - avatar
+ 3
maybe this will be your solution: for ( var i = 1; i <=100; i++){ if(i%3===0){ console.log ("fizz"); } else if (i%5===0){ console.log("buzz"); } else { console.log(i); } }
27th Jul 2017, 6:31 PM
Yaroslav Pieskov
Yaroslav Pieskov - avatar
+ 3
Thank you so much
27th Jul 2017, 6:36 PM
Peter Claver
Peter Claver - avatar
+ 3
book " Secrets of the JavaScript ninja"
27th Jul 2017, 6:40 PM
Yaroslav Pieskov
Yaroslav Pieskov - avatar
+ 1
Please could you recommend an in-depth javascript program book or tutorial for me?
27th Jul 2017, 6:37 PM
Peter Claver
Peter Claver - avatar