This code produces [5, 4], but if I switch the variable myArray with the variable i, the code produces [5, 4, 3, 2 , 1, 0]. This makes no sense to me. Is it possible for someone to explain to me how this works in a way I (a javascript n00b) would understand?
// Setup
const myArray = [];
// Only change code below this line
let i = 5;
while (myArray >= 0 && myArray <= 5) {
myArray.push(i);
i--;
}
console.log(myArray);
Challenge: Basic JavaScript - Iterate with JavaScript While Loops
This isn’t doing what you think it is doing. You are comparing the array to a number, so JS is implicitly converting the array to a number for you. Apparently, an empty array will be converted to the number 0 and an array with one number will be converted to the value of that number. But an array with more than one number can’t be converted to a number and will resolve to NaN. So your loop works while myArray is empty or has one number in it, which would explain why it is looping twice and pushing 5 and then 4 to myArray. But as soon as 4 is pushed to the array then it has two numbers and the while loop will terminate because the array now produces NaN when converted to a number.