JavaScript Loop for Even Numbers

‘Use any kind of JavaScript loop to print all the even numbers from 0 to 10 (inclusive).’

I can create a “for” loop, but I’m having trouble trying to figure out how to log the even numbers into this function. I know the function (i % 2 === 0) can do this, I just can’t figure out how to incorporate it.

Have you learned about if conditional statements?

if (condition) {
    // action if condition is truthy
}

I ask this because the same logic is applied in controlled loops such as for and while. The condition determines when to stop iteration of the loop.

We can structure a loop such that we don’t need to test inside the code body since we set the controls outside of that, (for) or set the control inside the loop (while) if the logic favors that approach.

    while (condition) {
        // code to execute
    }
    for (start; condition; step) {
        // code to execute
    }

The condition in both loops is the same.

let x = 0;
while (x < 10) {
    x++;
    console.log(x);
}
for (let x = 0; x < 10; x++) {
    console.log(x + 1);
}
2 Likes

You could implement the modulo check to see if the number is even for each number from 0 to 10, but mtf’s solution is better because it doesn’t require the extra code and processes.

1 Like

I actually hoped that my code would not be taken as a solution, but rather a template of sorts. There is still some thinking to be done. Please, let’s let the OP work through this process and respond to us with understanding or more questions.

1 Like