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

Alcibiades Montas
Alcibiades Montas
5,974 Points

Javascript Question: While Loop formatting?

Have the following questions about this piece of code I created in Javascript:

var i = 100;

while (i>5) { console.log (i); i--; }

1) this code is supposed to countdown to greater than 5 from a 100. However the console log spits out 6 twice.

2) How can I decrement in higher values than 5?

Thanks!

1 Answer

Jose Morales-Mendizabal
Jose Morales-Mendizabal
19,175 Points

1) The code is spitting out twice the number 6 because your positioning the decrement operator -- in the wrong side of the operand (in your case, the variable i ). When you put the -- AFTER the variable " i " like you have it, it subtracts 1 from 100 on the first iteration of the loop but it RETURNS the undecremented value, thus 100. When it reaches the end of the loop it outputs 6 twice because it subtracts 1 from 6 but instead of outputting 5 it logs out the undecremented value of 6. To get to 5 place the -- operator BEFORE i. That way the loop will subtract 1 in each iteration but it will return the actual subtracted value that you want.

2) If you want to decrement in higher values you need to code your counter as

i = i - x

//x being whatever value you want to decrement in. the counter below will count backwards 100, 90, 80 and so on

i = i - 10;