What is happening in this loop?

In one of the challenges it asks to use a while loop to fill an array of descending numbers. I know I can just use an ascending loop and unshift but this was my initial plan and I’m getting errors I don’t understand.

// Setup

var myArray = [x];

// Only change code below this line

var b = 6;

while(b > 0){

  myArray.push(b);

  b--;

  console.log(myArray[b]);

}

Output:
undefined
undefined
undefined
4
5
6

Like I understand if I get the wrong range of numbers or one of them is undefined because while loops do an extra iteration but why so many undefined?

What exactly is this?

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 (’).

And what is this? Is x defined somewhere else?

Sorry first time using forum.

X should not be there. It’s the setup for the challenge and I’m not supposed to change it, it’s an empty array.

var myArray = [];

OK, then we are back to Jeremy’s idea. What if you did:

console.log(myArray);

We don’t think that that b represents what you think it does.

1 Like

YES thank you so much. This helped me see it better. I was outputting the index not the array itself so of course the index of an array that it doesn’t have would be undefined.

var b = 5;

while(b > -1){

  myArray.push(b);

  b--;

  console.log(myArray);

}

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