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
jason chan
31,009 PointsSo how does this while loop work for 2^10
var result = 1;
var counter = 0;
while (counter < 10) {
result = result * 2;
counter = counter + 1;
}
console.log(result);
// → 1024
someone explain to me what's happening here?
kind of lost when result = result * 2;
why is var result = 1?
2 Answers
Nick Novak
2,517 PointsWhat we are essentially doing is taking 2^10 by running it as a loop.
First lets look at powers:
2^10 = 2*2*2*2*2*2*2*2*2*2 think of each * as a loop.
Each iteration of of result = result * 2 will times the next number by 2.
so lets break it down by each iteration:
iteration 1: result(1) = result(1) * 2; result = 2; counter =1
iteration 2: result(2) = result(2) * 2; result = 4; counter =2
iteration 3: result(4) = result(4) * 2; result = 8; counter =3
iteration 3: result(8) = result(8) * 2; result = 16; counter =3...
and so forth until our counter reaches 10 and the result equals 1024.
With result = 1, it has to be to get the correct results.
lets take the first example but make result = 0:
iteration 1: result(0) = result(0) * 2. result becomes = 0; counter =1
iteration 2: result(0) = result(0) * 2. result becomes = 0; counter =2
iteration 3: result(0) = result(0) * 2. result becomes = 0; counter =3...
and so forth until our counter reaches 10 and the result equals 0. result has to have a starting point at one for powers to work..
Jeff Lemay
14,268 PointsFantastic answer in comments
Nick Novak
2,517 PointsWhoops. I meant to place that in the answers section. I have it in there now.
jason chan
31,009 Pointsjason chan
31,009 Pointsthankyou very much!