The good/fizzbuzz!


#1

Continuing the discussion from The good/Fizzbuzz help:

Hi Leon! I have a question (redundant).
I keep seeing

if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz")

why are we using the "truth" setting of the equals sign?

i thought:

if (i % 3 || i % 5) {
console.log ("FizzBuzz")

Why won't that work?

-A Confused Student.


#2

@objectsurfer35864,

+++++++++ modulo ++ FizzBuzz ++++++++++++++++
Javascript has the so-called Remainder-operator %
is actually a modulo-operator
and if used it will return the rest-value.

9%3 You read it as nine modulo three is zero, as 9 divided by 3 has NO rest-value.
22%6 You read 22 modulo six is 4, as 22 divided by 6 will leave you with rest-value 4
10%5 You read 10 nodulo five is zero, as 10 divided by 5 will have NO rest-value

In this section you have to figure out
(i%3 === 0 && i%5 === 0) to display FizzBuzz // if (imodulo 3 equals zero AND imodulo 5 equals zero)
(i%3 === 0) to display Fizz // else if (i modulo 3 equals zero )
(i%5 === 0) to display Buzz // else if (i modulo 5 equals zero )
AND
if none of the above display i //else display i

You will have to use an IF ELSE-IF ELSE-IF ELSE-statement
within a for-loop.

google search
== the Book ==
javascript remainder operator site:developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

== discussions / opinions ==
javascript remainder operator site:stackoverflow.com
http://stackoverflow.com/questions/4467539/javascript-modulo-not-behaving

== guidance ==
www.crockford.com
http://javascript.crockford.com/survey.html
http://javascript.crockford.com/code.html


#3

@objectsurfer35864,

As you now know
if you are using the condition
(i % 3 || i % 5)
you can end up with a condition
( 0 || 4 )
which the Javascript Interpreter would interprete as
( falsy || truthy )
https://developer.mozilla.org/en-US/docs/Glossary/Truthy
https://developer.mozilla.org/en-US/docs/Glossary/Falsy


#4

Lets go back to principle first, IF statement cares about the value TRUE or FALSE (in sense, if condition is TRUE, execute the code, if FALSE, skip, or if available, go to ELSE code)

if (i % 3 === 0 && i % 5 === 0) {

This is recommended because basically it is (condition1 && condition2) and each condition will result in TRUE or FALSE, and so, it is clear what will be final result: TRUE/FALSE.
i % 3 === 0 simply wants to check if i is divisible by 3.

meanwhile

if (i % 3 || i % 5) {

will be wild, since it is basically (condition1 && condition2) but each condition is mathematical calculation that will result in any number, can be 0 (considered FALSE) but there will be many chances that this is NOT 0 , and any number which is not 0 is considered TRUE. So you can see how wild the result will be.

In programming you generally like things to be under control. The easier the better.