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 Create a for Loop

Ryan Moye
Ryan Moye
4,107 Points

I can't figure out how to set up this for loop

I wrote the code and I think it's mostly right, but I can't tell.

script.js
var i = 0;
for ( i = 4; i <= 156; i += ) {
  console.log(i);
}

2 Answers

Antonio De Rose
Antonio De Rose
20,884 Points
var i = 0;
for ( i = 4; i <= 156; i += ) {
  console.log(i);
}

//you have already setted up the loop nicely, except for the incrementer which needs to added by 1
//and it would be a better practice to declare it within the brace, rather than declaring outside


//var i = 0; // this is redundant
for ( var i = 4; i <= 156; i += 1) {
  console.log(i);
}


// var i = 4 ->entering in the loop
//i <= 156 -> checks for the condition, if it is true, then go to the statement
//i+=1 -> increment it

//and finally, when i is 157, at that time, it will check condition, like below
//i <= 157
//it will exit from the { } block
Alexander Solberg
Alexander Solberg
14,350 Points

You are declaring the "i" variable outside of the loop, which is what we typically do with a "while" loop, not in a "for" loop though. In a "for" loop, you declare the variable(most commonly "i") within the condition of the loop.

Also, "i +=" is indicating that "i" is supposed to be added with some value, however, you aren't passing any value. It should be something like(ignore quotes) "i += 1", or better yet, "i++"(if you simply increment by +1).

The following code will pass the challenge.

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