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 For Loops

H Yang
H Yang
2,066 Points

Challenge Task

Hello,

I tried solving the challenge task with this solution:

var counter = "";
for (var i = 4; i <= 156; i += 1) {
  counter += i;
}
console.log( counter );

Didn't work, told me that it only called the console.log once.

Why does this one work better?

var counter = "";
for (var i = 4; i <= 156; i += 1) {
  console.log( i );
}

It's different from the one in the video and places the console.log inside the loop's code block.

2 Answers

Umesh Ravji
Umesh Ravji
42,386 Points

Hey Henry,

var counter = "";
for (var i = 4; i <= 156; i += 1) {
  counter += i;
}
console.log( counter );

This does only log to the console once. You are first creating a counter variable before your loop, then you keep building on that variable each time in the loop. Then at the end you log all of it out at once (what you have ended up with is one long string of all the numbers, 4567891011121314...).

The secound one logs a number at each iteration: 4 5 6 7 ...

The counter variable isn't doing anything in the secound case.

H Yang
H Yang
2,066 Points

Thank you Umesh. I wrote the first one to follow the example of the video which separated out each iteration with <div> </div> tags. Would that have been an acceptable solution?

Umesh Ravji
Umesh Ravji
42,386 Points

I'm not sure, challenges tend to require specific answers at times.

If you want to, you can go back to the challenge and enter anything different to have a look, it won't have any bearing on your points/progression if you get it wrong after completing it.