Reputation: 219
let number = 0;
while (true) {
if (number%2 === 0) continue;
console.log(number);
number ++;
}
I wanted to infinite loop to print out only odd numbers. But this doesn't seem to work. What am I doing wrong?
Upvotes: 0
Views: 7814
Reputation: 500
Let's have a brief understanding of the code execution.
When the following code is executed...:
let number = 0;
while (true) {
if (number%2 === 0) continue;
console.log(number);
number ++;
}
...the following happens:
Simply put, it never goes forward to the console.log and the number++ line. This is why your code isn't working.
The code from others work because the control actually moves forward in the code and never actually becomes stuck in the above loop.
Upvotes: 1
Reputation: 1658
Whatever number is, increment it first. Otherwise, when it is even, it never reaches to number++ any more.
let number = 0;
while (true) {
number ++;
if (number%2 === 0) continue;
console.log(number);
}
Upvotes: 1
Reputation: 1529
You should increment the number when it is even
also, to check the next number and so on:
let number = 0;
while (true) {
if (number%2 === 0){
number++;
continue;
}
console.log(number);
number ++;
}
Upvotes: 1
Reputation: 5264
let number = 0;
while (true){
if (++number % 2 == 1){
console.log(number);
}
}
no need a continue
statement, just check the remainder is 1 the print the value in the loop.
you can further shorten the if condition as if (++number % 2)
Upvotes: 1
Reputation: 1218
Try this code
let number = 0;
while (true) {
if (number % 2 != 0)
console.log(number);
number ++;
}
The code you're using will not work because you defined number=0
and then you're checking the condition if(number%2==0) continue;
so this condition will always return true because the number is defined 0 and the number++
will never increase.
Upvotes: 1