Basic JavaScript - Iterate with JavaScript While Loops

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**
// Setup
var myArray = [];
var i = 0;

// Only change code below this line
while(i < 6) {
myArray.push(i);
i++;
// should return 0,1,2,3,4,5
// it return 1,2,3,4,5,6
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0

Challenge: Basic JavaScript - Iterate with JavaScript While Loops

Link to the challenge:

Are you sure about this?

var myArray = [];
var i = 0;

// Only change code below this line
while(i < 6) {
myArray.push(i);
i++;
// should return 0,1,2,3,4,5
// it return 1,2,3,4,5,6
}


console.log(myArray);//[ 0, 1, 2, 3, 4, 5 ]

if we switch lines like that

i++;
myArray.push(i);

it will be

// in for loop it returns 0,1,2,3,45,

for (let i = 0; i < 6; i++) {
  console.log(i);
  //returns 0,1,2,3,4,5
}

// and in python it returns
/*

i = 0
array = []

while(i < 6):
    array.append(i)
    print(i)
    i+=1
    
print(array)
returns 0,1,2,3,4,5

*/

why does while and for loop in javascript have different output with same conditions?

Does it?
I am pretty sure that this loop from your original post

returns

I just tested it like three times)

this is the results
when i try it on javascript compiler online

well, when you are testing for loop, you are logging i

when you are testing while loop you are logging array

Your tests itself are different
Try logging similar stuff for both loops maybe

let i =0 ;
while(i < 6) {
console.log(i);
i++;
}
/*
Output:

0
1
2
3
4
5
*/

now both of them returns 1,2,3,4,5,6, why does it not push zero when zero is the first number and is above the increment line?

thanks, i get it now
the print from the push are different from the numbers in the array itself

you can modify your python tests to print not i, but list.append(i) and see what happens there

the output was none. when printing list.append(i)

that’s my bad. I meant list as data type.

in your original python code

you called your list:

try something like

i = 0
array = []
while(i < 6)
print(array.append(i))
i+=1

Double check syntax, I didn’t use python for a while

yeah the result is none printed six times

the result is
None
None
None
None
None
None
[0, 1, 2, 3, 4, 5]

Look at the return type for the method.

You might have noticed that methods like insert , remove or sort that only modify the list have no return value printed – they return the default None . 1 This is a design principle for all mutable data structures in Python.


Not a Python guy BTW but I assume it applies to append as well,

2 Likes

note that push returns the length of the array, so you are pringing the length of myArray after pushing, not i

1 Like

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