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?
You used the wrong looping construct. It should be a
for
, notwhile
. Also note that it's semicolons between the clauses, not commas:What you have is this:
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 thati
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 thewhile
. Sincei
is 0, which is falsy, the loop body never executes.Note that if you had used
++i
instead, it would make no difference in thefor
case, but yourwhile
version would loop forever instead of not running at all, sincei
would already have been incremented to 1 the first time it was tested for truthiness.