FizzBuzz in Javascript: the code won't execute or print at all

94 views Asked by At

Have been playing around with the FizzBuzz problem, and I am wondering why the following code won't execute, nothing gets printed to the console.

var i = 0;
while (i = 0, i < 100, i++ ) {
    if ( i % 3 === 0) {
        console.log("Fizz");
    } else if ( i % 5 === 0) { 
        console.log("Buzz");
    } else {
        console.log(i);
    } 
}

What am I missing?

2

There are 2 answers

0
Mark Reed On BEST ANSWER

You used the wrong looping construct. It should be a for, not while. Also note that it's semicolons between the clauses, not commas:

for (i=0; i < 100; i++) {

What you have is this:

while (i = 0, i < 100, i++) {

The comma just evaluates the left side, throws the result away, and then evaluates the right side. So that sets i to 0 (and discards the zero value returned by the assignment), tests that i is less than 100 (but does nothing with the true value returned by the comparison), and uses the value of the last expression (i++) as the loop condition for the while. Since i is 0, which is falsy, the loop body never executes.

Note that if you had used ++i instead, it would make no difference in the for case, but your while version would loop forever instead of not running at all, since i would already have been incremented to 1 the first time it was tested for truthiness.

0
holl On

I believe you are simply confusing the way you make 'for' and 'while' loops. You've built your 'while' like you would a 'for'!

Think of it this way: when you write a while loop like this:

while(i<100) {

You're saying, while (this condition is true). All that you need between the parentheses is a statement to determine whether it's true or not. Somewhere in the loop, you (usually) would need to change the value of i, or you'd (probably) get an infinite loop.

Now, the for loop, we'll need more information between the parenthesis... we'll need all the information that determines the amount of loops we'll take. Just like you've written it there, we're writing for (when my variable equals this; Loop until this condition is true; change the variable like this).

Generally, this means that 'while' provides more flexibility in how you determine the logic of your loop, but a 'for' loop is probably the easiest to read.