factordog - 10 months ago 29

Javascript Question

I have a very basic loop that I currently don't understand fully.

`for (var i = 1; i <= 100; i++) {`

if (i / 3) {

$(".counterWrapper").append("fizz" + "<br>");

}

else {

$(".counterWrapper").append(i + "<br>");

}

}

Basically I am wanting it to only return the word 'fizz' if the variable i's value is divisible by 3. Currently it is only returning the word 'fizz', so it would seem that it is getting stuck in the if loop and running it each time.

This is a very simple loop, but I think it might do with the way I am doing my comparisons. What would be the best way in order for it to work out if the variable i is dividable by 3?

Answer

In javascript true and false are treated uniquely. 0 is false, any other number is true. Take a look at:

```
if (i / 3) {
$(".counterWrapper").append("fizz" + "<br>");
}
```

What you're saying is if i divided by 3 append fizz. So when looping:

```
if (0 / 3) // this would be 0 so it would be false
if (1 / 3) // this would not be zero so it is true
if (2 / 3) // this would not be zero so it is true
```

and so on.

You need to use modulo (%) which checks for remainders and use a comparison.

```
if (i % 3 === 0)
```

If you ran through the loop

```
if (0 % 3 === 0) // remainder is 0, so it is true
if (1 % 3 === 0) // remainder is 1, so it is false
if (2 % 3 === 0) // remainder is 2, so it is false
if (3 % 3 === 0) // remainder is 0, so it is true
```