freeCodeCamp Challenge Guide: Iterate with JavaScript While Loops

freeCodeCamp Challenge Guide: Iterate with JavaScript While Loops
0

#1

Another type of JavaScript loop is called a while loop because it runs while something is true, and stops once that something is no longer true.

var ourArray = [];
var i = 0;
while(i < 5) {
  ourArray.push(i);
  i++;
}

#2

That’s exactly what I came up with too. Didn’t work though.
removing the blank array “myArray” that was written there helped a little but after the console returned a 4 instead of the “[]”(without the quote), that it returned before.

Can anyone help us?


#3

Can you paste your code here so we can have a look? :slight_smile:


#4

It’s exactly the same code as the OP…[quote=“Rafase282, post:1, topic:18220”]
var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
[/quote]


#5

I think it’s looking for us to use “myArray” When I used the following, it passes correctly:

// Setup
var myArray = [];

// Only change code below this line.
var i = 0;
while(i < 5) {
myArray.push(i);
i++;
}


#6

Just so you all know in case you haven’t noticed, this shows how to use what they are asking, it is not however, necessarily the right answer that you can just copy paste.

I originally created these long ago but I remember not putting the right answer as the example even though in many cases it would be the same or very similar.


#7

yup, I derped like in the OP I guess. I changed my code from ourArray to myArray and it worked. Of course maybe he did his on purpose I’m the one that derped… anyway, thanks guys!


#8

Your github wiki has helped me tremendously in the past. When I get stuck, it’s the first place I turn. I like how they are so similiar it helps me understand. it’ helps with the streategy of problem, solving sometimes and it also helps tro show me that sometimes I’m way off whewre I should be.

Some of the lessons have apparently been changed since you did your work but even still, I’m still learning.

So please don’t feel like you need to defend yourself. You’ve helped a ton (at least for me and I suyspect, many others).


#9

I’m glad it has helped you plenty.


#10

remember the numbers go in myArray = [1,2 etc…]


#11

you can run it like this as well, without using push which adds the item to end of array. Instead you can index it by its value at taht position

// Setup
var myArray = [];

// Only change code below this line.
var i = 0;
while (i<5) {
  myArray[i] = i;
  i++;
}

#12

You could do it like this:

// Setup
var myArray = [];

// Only change code below this line.

var i = 0;
while(i <= 4) {
myArray.push(i);
i++;
}


#13

Note the importance of the increment ( i++) after the .push and not before it. If the i++ is added before the .push you will get the output of 1-5 and not 0-4.

var myArray = [];
var i=0;
while (i<5){
myArray.push(i);
i++;

}