Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Refactor Using a Loop

what is wrong with my code?

var i; for ( var i = 2; i => 12; i += 1) { console.log(i) }

i need it to print 12 times from 2 to 24.

2 Answers

Brandon Oakes
seal-mask
.a{fill-rule:evenodd;}techdegree
Brandon Oakes
Python Web Development Techdegree Student 11,501 Points

The challenge wants you to print every even number between 2 and 24 into the log. Your code says I =2 and run this loop if i is greater than/equal to 12, which will never happen then.

The code below says: for var i=2 (this 'i' variable currently equals 2)

run this loop while i is <= 24 (less than equal to 24)

i+=2 (and add 2 to every time, so that when I is printed each time in the for loop it will be 2, then 4, then 6, etc until i is greater than 24)

 for ( var i = 2; i <= 24; i += 2) { 
    console.log(i) 
 }

Let me know if this helps

Thank you!

When you use for loop the var inside the loop is local to that loop.

Breakdown 4 steps

1 var i = 2. Starts the varivale with value of 2

2 i < 24 condition true as 2 is less than 24 (when false the loop will stop step 3)

3 ++2 or +=2 this will increment by 2 the var i that you declared in the loop. . 4{} code block will run each time the loop condition is true.

Thank you!