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

Can someone please explain how this works?

I tried copying some code for the for loop on this one but it's saying that I am logging numbers between like 1294 and 239503 . and i made it go from 4 to 156. Please explain this to me. I don't get how math works like that.

script.js

1 Answer

Tony Nguyen
Tony Nguyen
24,934 Points

Hey Kenny,

So, here is what the question is asking: "Create a for loop that logs the numbers 4 to 156 to the console. To log a value to the console use the console.log( ) method."

In order to understand this, we must understand what each statement means in the for loop.

Here's the for loop:

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

First we declare a random variable "i", it could be anything you want, however it's common to see programmers use the variable "i". We declare this because the question asks us to log a number from 4 to 156. So we'll start with 4.

The second statement in the for loop is checking if it is true or not. So in the first iteration, it first asks itself is "i" less than or equal to 156? If so, then run the code block inside.

The third statement increments our variable "i" by 1 each time, and it will keep doing this until the middle statement inside our for loop is no longer true.