Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript learning, while if

Tags:

javascript

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--;
}
like image 819
caspe_ghost Avatar asked Dec 08 '22 06:12

caspe_ghost


2 Answers

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.

like image 70
Pointy Avatar answered Dec 10 '22 20:12

Pointy


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.

like image 29
J.D. Pace Avatar answered Dec 10 '22 19:12

J.D. Pace