Order of code in while loop

Hi

Can someone clarify for me please why in the following code the i increment function come after the push the code to push the value of i?

   var myArray = [];
   var i = 0;
   while( i <= 5 && i >= 0) {
       myArray.push(i);
       i--  ;   
}

The purpose of the code is to take i and take one off each time for 5 consecutive times and add each value to the array.

Another question I have is using for in the loop.

var myArray = [];

for(var i = 1; i <= 5; i++) {
myArray.push(i);
}

The above works but why doesn’t it work as the previous piece of code and setting i to 0 if it is being incremented by one THEN added to the array.

The code is suppossed take i and add one each time until 5 s reached and adding each value on the way from 1 to 5 into the array.

But i =1

after the first loop runs it will be 2 thats added no?

Could

**Your code so far**

// Setup
var myArray = [];
var i = 0
while(i <= 5 && i >= 0){
myArray.push(i)
i--
}

// Only change code below this line
**Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74.

Challenge: Iterate with JavaScript While Loops

Link to the challenge:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.