this may seem stupid to some, but please try and help me see sense here, I'm currently learning javascript and one of my challenges is as follows
In countdown.js below, modify the while-loop with a conditional that will only allow a number to be printed if it is even. Your results should be the even numbers from 10 to 2 descending. Think carefully about how your code might decide if a number is even…
If I use the code below I get the answer 9, 7, 5, 3, 1, but if I change it to num + 1 in the log out it works. I thought the decrement would occur after the log out put?
var num = 10;
while (num > 0) {
if (num % 2) {
console.log(num); // can't be right??????
}
num--;
}
The test in your if
statement, num % 2
, is true when the value in "num" is not divisible by 2. The %
operator gives the remainder after a division, so when the remainder is non-zero, it's true
.
If you want even numbers, use !(num % 2)
, which will be true
when the remainder is zero, or perhaps more explicitly num % 2 === 0
.
0 == false, and 1 == true. % division returns the remainder, so 3 % 2 = 1, which evaluates to true. Negate your comparision: if( ! num % 2 )
;
Alternately, use if( num % 2 === 0 )
, which may be more clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With