What is wrong with this? Why isn't it working?

What is wrong with this? Why isn't it working?
0

Tell us what’s happening:

Your code so far


// Setup
var myArray = [];

// Only change code below this line.

var i = 0;
while(i < 5) {
myArray.push(i);
i++;
}
close.log(myArray)

Challenge: Iterate with JavaScript While Loops

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops#

What do the failing tests say? What other solutions have you tried?

// running tests

myArray

should equal

[5,4,3,2,1,0]

. // tests completed // console output [ 0, 1, 2, 3, 4 ]

.push() adds an element to the end of an array, so you are creating the array [0,1,2,3,4] instead of [5,4,3,2,1,0].

I don’t understand.

I did exactly like the video, a few times

This is what your code is doing:

  • It starts with an empty array and i set to 0.
  • It begins the loop:
    • The array becomes [0] because i is 0. Then i becomes 1.
    • The array becomes [0,1] because the value of i (1) is pushed to the end of the array. Then i becomes 2.
    • This repeats until i becomes 5. At that point the array is [0,1,2,3,4] because every value less than 5 has been pushed to the end of the array.

That I understand. Why isn’t it working?
What am I supposed to do?

If you understand how it is currently working to create an array that starts at 0 and ends at 4, how can you change your logic to create an array that starts at 5 and ends with 0?

var i = 5;
while(i > 0) {
myArray.push(i);
i++;
}

That will create an infinite loop because i will always be larger than 0. Your array will start with [5,6,7,8…] and continue until the browser crashes.

I do not understand, I’m lost.
How do I add it to 5?

I’ve tried this as well, and it still doesn’t work

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

@Johny05 Your code starts with i = 0, so the first value pushed to myArray will be 0. The second number will be 1, because i++ assigns the value 1 to i, and so on and so on. What number should you start i at to accomplish what the instructions ask? Also, what condition in the while loop should occur to stop looping. Finally, how do you need to adjust the value of i at the end of the for loop code block, so that i decreases by 1 each time?

Figured it out.

var i = 5;
while(i > -1) {
myArray.push(i);
i–;
}

Congratulations on working it out.