Jahod1
July 19, 2020, 6:11pm
1
Tell us what’s happening:
var i = 0;
while(i < 6) {
myArray.push(i);
i++;
}
console.log(myArray)
Your code so far
// Setup
var myArray = [];
// Only change code below this line
var i = 0;
while(i < 6) {
myArray.push(i);
i++;
}
console.log(myArray)
Your browser information:
User Agent is: Mozilla/5.0 (X11; CrOS armv7l 13020.87.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.119 Safari/537.36
.
Challenge: Iterate with JavaScript While Loops
Link to the challenge:
Learn to code. Build projects. Earn certifications.Since 2015, 40,000 graduates have gotten jobs at tech companies including Google, Apple, Amazon, and Microsoft.
Hi and welcome to the forum.
It looks like you mostly have the right idea, but you are putting the numbers in in increasing order.
I’d look at changing i
from increasing to decreasing on each iteration.
To do this you will need to change the initial value of i
, the loop exit condition, and the second line inside your loop.
I hope this helps!
1 Like
If we log your array after the code has run we get this:
console.log(myArray) // [ 0, 1, 2, 3, 4, 5 ]
This is the test requirement:
myArray
should equal [5,4,3,2,1,0]
.
1 Like
pyguss
July 19, 2020, 8:12pm
5
@Jahod1 Try examining the example given in the lesson before attempting the challenge. The code in the example starts the loop from 0 and adds 1 every time until the while condition is not valid anymore. For the challenge, what you need to do is the opposite. You should start from the top (which is 5) and loop through until you reach 0 (inclusive) - count downwards and add them into the ‘myArray’! So first push number 5 into ‘myArray’, then number 4, and so on.
I hope that is clear!
1 Like
Jahod1
July 20, 2020, 5:27am
6
var i = 6;
while(i < 5) {
myArray.push(i);
i++
}
ILM
July 20, 2020, 8:01am
7
that will never run
notice how your i
starts at 6 but the loop condition is i < 5
that means that it is false even before going to the loop and the loop never run
Jahod1
July 20, 2020, 6:33pm
8
idk lol i try everything var i = 0;
while(i < 6) {
myArray.push(i);
i++
}
console.log(myArray)
ILM
July 20, 2020, 6:41pm
9
now you are back to making the numbers go up
think about it, how do you count from 5 to 0?
you start at five, decrease by one each time, and then when do you stop?
Jahod1:
i++
The statement i++
means ‘increase i
by 1’. You need to make i
decrease . Do you remember a freeCodeCamp challenge showing you how to make a variable decrease ?
ILM
July 20, 2020, 8:11pm
12
now you got an infinite loop because you start from 5, than keep increasing i
with i++
, and i >= 0
will always be true
if you start at 5 and wants to go down to 0 you need to decrease the value of i