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

Bogoljub Milovanoski
Bogoljub Milovanoski
3,431 Points

I cant solve this problem: Create a for loop that logs the numbers 4 to 156 to the console. To log a value to the consol

Help

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

2 Answers

Saleh Ben Nakhi
Saleh Ben Nakhi
7,305 Points

Your approach is a clever one, but I can see the reason for confusion. your number starts at 4 and should stop at 156, therefore the loop should go for 152 times. So your if statement should be

for (var i = 1; i <=152; i++) { console.log(number); number += 1; }

another approach could be for (let i = 4; i <= 156; i++) { console.log(i); }

note: let is a new way to declare variables in JS, it works as var would.

Aj Broman
Aj Broman
2,668 Points

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

but yeah let is similar to var and const is how to set a var that won't(can't?) be changed // constant