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 trialWally Bryan
4,350 PointsIs this a flaw that has been overlooked in JS? or am I just dumb hahah
here is the code, very basic,
for (var j = 0; j <= 100; j += 10) {
console.log( j );
}
prints 0,10,20,30,40,50,60,70,80,90,100 :) (very simple) -
But isn't this wrong?
The program runs - create J, J is 0, Is J less than or equal to 100? yes (currently); so add 10 to J, J is now the value of 10.
But the program prints 0 (Zero) first? At the point that the program is told to print anything, the value of J is now 10, not 0
P.s.
I could have missed something, so be gentle with my limited knowledge :P but this seems flawed if i have not missed something.
1 Answer
Jason Anders
Treehouse Moderator 145,860 PointsHey Wally.
Well, you're not dumb, and this is actually a very good question. The reason it prints out 0
first is because of the way the for loop
works... it's not as linear as you'd think.
The "For Loop"
- The first thing that happens is the variable is created and the value assigned. Here it's called
j
and the initial value of Zero is assigned. - The loop now checks to see if the condition is met (a true or false response). Here, it's checking to see if
j
is less than or equal to 100. Right now it's zero, so the condition receivesTrue
. - Because the loop received a True response... now here where many get tripped up... the loop executes the code block in the curly braces. Here, it's the
console.log()
method, and because the value is still zero (the increment hasn't run yet), the console logs out0
. - Once the code block has been executed, the final part of the
for loop
is run... here incrementing the value ofj
by 10, and the loop starts over again. - This time the variable isn't created, this only happens the first time, instead the value is changed to the new value of the previous iteration's increment.
I hope this makes sense and helps! :)
Keep Coding!
Jennifer Nordell
Treehouse TeacherJennifer Nordell
Treehouse TeacherHi, Wally! I added some markdown to your code so that it's a little more readable. If you're interested in learning how to do this, take a look at the Markdown Cheatsheet link at the bottom of the "Add an Answer" section!