Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

abhi reddy
abhi reddy
1,636 Points

for (i=2;i<=24;i*=2){ console.log(i); }

can some one help me

script.js
for (i=2;i<=24;i*=2){
   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

andren
andren
28,558 Points

The problem is that the sequence the challenge wants you to reproduce (2, 4, 6, 8, 10, etc) goes up by two each step, it is not multiplied by 2 each step, doing that results in a sequence like this (2, 4, 8, 16, 32, etc).

Your code is mostly correct, you just have to change "i*=2" to "i+=2" this will increase i by two each loop, which gives you the desired result.

Lachlan ∆
Lachlan ∆
8,026 Points

Try this:

    for (i=2; i<=24; i++){
       console.log(i);
    }
Indranil Tiwary
Indranil Tiwary
9,341 Points

A2A

Try this mate:

  1. if you need an output of 2,4,6,8.. i.e. differences of two (2) till 24..
for ( int i = 2; i<=24; i+=2) {
    console.log(i);
}
  1. if you need an output of 2,3,4,5.. so on with increment of one..
for (int i=2; i<=24; i++){
    console.log(i);
}

Explaination:

for loop works as..

for(initialization; condition; re-initialization)

so in re-initialization we increment or decrement our initialized value such that we satisfy the condition and break out of the loop. Hope I helped.. Please reply with any further queries.. Glad to help..