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

Kim Dallas
Kim Dallas
11,461 Points

I'm completely lost with this one.

how can I write a loop that repeats the console log every 2 times? the example used random numbers?

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>

2 Answers

Just taken a look at the actual code challenge rather than solving the issue in my REPL.

The HTML doesn't need to be touched. You just need to replace all the console.log lines in the js file with the for loop.

In my example above I defined the variable using the let keyword, although this is best practice, the code challenge only passes if you use var, So the "correct" answer is:

for (var i = 2; i <= 24; i += 2) {
  console.log( i );
}
Kim Dallas
Kim Dallas
11,461 Points

thank you very much berian

So the best way to complete this task is to use a for loop.

The syntax for a for loop is as follows:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

In the first statement, we want to define our variable. As this is an integer, we'll call this i. This is executed once. As this integer will increase, we would need to use a let variable.

In the second statement, we want to declare our condition. Here we want to stop printing to the console when the integer is greater than or equal to 24.

In the third statement we want to increase our integer by 2 every time the code block has been executed. This will run until the condition in the second statement becomes false.

for (
let i = 2; //Define variable.
i <= 24; //Declare condition
i += 2  //Increase int when code block is executed
) {
  console.log( i ); //code block to be executed
}

So the answer would look like:

for (let i = 2; i <= 24; i += 2) {
  console.log( i );
}
Kim Dallas
Kim Dallas
11,461 Points

i've tried everything with this one. it still won't work. nothing in the html file references it. is that why it won't work?