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

Please explain how the sum amounts to 1275

var sum = 0; var number= 1; while (number <=50) { sum += number; number++; } alert("Sum = " + sum);

2 Answers

In reference to your question.

<script>
var sum = 0;
var number = 1;
while (number <= 50) {
  sum = sum + number;
  number++;
}
alert("Sum = " + sum);
</script>

What is happening behind the scenes is your while loop is going to run as long as it is true. So for the while loop to top number needs to reach 51, for it to become false.

each time threw the loop you are saying sum = sum + number; and then also number + 1; so first time threw the loop it looks like this

 sum = 0 + 1     // sum = 1
number + 1     // number = 2

Second time threw the loop now is this

sum = 1 + 2    // sum = 3 
number + 1    // number = 3

third time threw the loop

sum = 3 + 3    // sum = 6 
number + 1    // number = 4

And so on... giving you sum equaling 1275, by time the while loop is done.

Thank you for the reply. Its making sense now. So var number acts as a counter which stops at 49. So when would this type of function be used in the real world?

Correct, well actually it stops at 51, and the only reason it stops at 51 is due to the <= since when it run threw at 50. 50 = 50 and yes, that is true since 50 is qual to 50, so it will try again with 51. Since 51 is not less than or equal to 50 then that final statement is false and the loop ends.

As for you question about using it in the real world,

It could be used in a media player like this here

<script>
// music player loop:
while (user does NOT press stop AND NOT end of playlist) {
  get the next song
  play the song
}
</script>

something along these lines.