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

while loop < <= =

hi everyone, I have a question on loop and how often it runs. This is the example.

function getRandomNumber(upper) { return Math.floor( Math.random() * upper ) + 1; }

let counter = 0; while ( counter <10 ) { counter +=1; document.write ( ${getRandomNumber(35) }); }

My question is on while ( counter <10 ) and how many times the loop runs

1) while ( counter <10 ) runs 10 times 2) while ( counter =<10 ) runs 11 times 3) while ( counter =10 ) error.

on example 1) <10 I would expact it would run 9 time and with =<10 that it would run 10 time. But why does the first one runs 10 times and the second 11.

and why is it that =10 gives an error?

i hope to hear from u !

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,858 Points

Hi Max van den Berge

Those are great questions.

So, for the first one "why does it run 10 times instead of 9?"
==> All code uses zero indexing. This means that it starts counting from zero not one. So <10 will run: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 which is 10 times.

The second question of why <= 10 runs 11 times is the same reason as above. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.

The third one about the =10 error. If you tell the loop to only run when the variable equals a number, unless it's the first number, you'll encounter an error, because the loop can never run. The count will start at zero, but is told to only run when the count is 10, but it can't run, so it will never get to ten to run. (paradox time) Make sense?
Essentially a loop is used to run a series of executables more than once, so you'd never have a hard definitive number like that anyways... always a range, never an equals to.

Keep Coding! :) :dizzy:

thx, is really helpful!!