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 Introducing the Practice

While loops

What am I doing wrong here?

```let i; let text;

// 1. Write a while loop to build a string of numbers from 0 to 4, // separated by spaces, and store the string in the variable text. print('1st Loop:'); text = '';

// Write 1st loop here:

while (i <= 4) { i++; text += i + ' '; }```

2 Answers

You need to assign a value to your initial i variable

let i = 0 // Sets the variable to equal 0 as a number so that it may be incremented
let text = '' // Sets the variable as a string

while (i <= 4) {
    i += 1 // Increments the variable
    text += i // adds the number to a string (which results in a string)
}

(You really are only missing the initial assignment for the variable i)

thank you, I thought I tried this but I suppose not

Phil Sta
Phil Sta
3,805 Points

Hi Joe,

I am stuck with this one too... what if the counting starts with 1 and not 0 (or counts down from 50 to 0) ... what value do you assign to the initial variable i?

Alicea Hotchkiss
Alicea Hotchkiss
5,956 Points

I know this is way old, but hopefully it may help anyone else struggling with this. There are two ways I know of to do this:

1 - initialize the variable at which number you want the count to start. So if you want your count to start at 1, it would be:

let i = 1 or var i = 1

The output in that case for this program would be: 1 2 3 4

2 - increment the count before adding it to the counter. That would look like this:

var i = 0;

while ( i <= 4 ) { i += 1 ; text += (i + " "); }

Following the code shows that as long as the variable i is less than or equal to 4, the program will increase the variable by 1 and then add it to the text string. This will also result in the output of 1 2 3 4.

Hope that helps!