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

Why doesn't this work???

for ( ) { console.log(4, 156) }

script.js
for () {console.log(4))}

1 Answer

Tabatha Trahan
Tabatha Trahan
21,422 Points

The for loop needs a few pieces of information in order to run: it needs an initial value to start with, then a condition to check to see if it should continue on with the body of the loop, then it needs the control variable to change by either increasing or decreasing in value. The challenge is asking to print the numbers 4 up to 156, so you would start your loop out like this:

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

the var i = 4 is the initialization of your control variable, the i <= 156 is the condition statement that is checked before the body of the loop is executed, and i += 1 is where you increment the control variable. If you don't do this part, you can end up with an infinite loop. The console.log(i) is the statement within the body of the loop to execute as long as the condition is met. Once the value of i is greater than 156, you will jump out of your loop.

Thanks man