JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Refactor Using a Loop

The code below logs all of the even numbers from 2 to 24 to the JavaScript console. However, there's a lot of redundant

I've been at this, and it's killing me I can't figure it out.

script.js
for (  i = 2; i <= 25; i++) {
    console.log(i);

}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

3 Answers

Rachel Lev
Rachel Lev
14,284 Points

You have to add 2 to i in order to get the even numbers, and i should be less or equal to 24 not 25:

for (i = 2; i <= 24; i += 2) {
console.log(i);
}
Adam Beer
Adam Beer
11,267 Points

No one learns from the finished code.

Mukhammadkhon Tadjiev
Mukhammadkhon Tadjiev
3,527 Points

Why do we need += in the end of the code within () ? Thanks

Adam Beer
Adam Beer
11,267 Points

Challenge Task 1 of 1

The code below logs all of the even numbers from 2 to 24 to the JavaScript console. However, there's a lot of redundant code here. Re-write this using a loop.

console.log(2);
console.log(4);
console.log(6);
console.log(8);
and so on...

And that's how your code work:

for (  i = 2; i <= 25; i++) { // In other words, i++ equal to i += 1
    console.log(i);

}

//the output
console.log(2);
console.log(3);
console.log(4);
console.log(5);

You are so close but it grows badly. This should be corrected and i <= 24. Hope this help.

for ( var I = 2; I <= 24; i+=2 ) {
 console.log(i);
}

Hope this help Cheers!

Adam Beer
Adam Beer
11,267 Points

And again, No one learns from the finished code. Second, your first two I is capitalized, and the last is lowercase, why? Now your code doesn't work.