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

Maima Kemokai
Maima Kemokai
1,928 Points

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

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.

script.js
console.log(2);
console.log(4);
console.log(6);
console.log(8);
console.log(10);
console.log(12);
console.log(14);
console.log(16);
console.log(18);
console.log(20);
console.log(22);
console.log(24);
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
Brendan Whiting
Brendan Whiting
Front End Web Development Treehouse Moderator 84,129 Points

Is there something you need more clarification on? What have you tried to solve the problem so far?

2 Answers

Piotr Manczak
Piotr Manczak
Front End Web Development Techdegree Graduate 20,763 Points

Solution nr 1:

for ( var i=2; i<=24; i += 2 ) {

console.log(i);

}

OR you can:

i = 2;

do {

console.log(i);

i += 2;

} while ( i<=24 )