Iterate with JavaScript For Loops - Challenge

I apologize for creating a new Topic, but couldn’t figure out how to comment or ask questions on the existing Topics.

Anyway, my question is about the Iterate For Loop challenge below:

var ourArray = [];

for (var i = 0; i < 5; i++) {
  ourArray.push(i);
}

How come the array will produce [0, 1, 2, 3, 4] and not [1, 2, 3, 4] ?

I thought the i++ at the end would take the initialized variable of 0 and make it a 1 and push 1 unto the array.
I can force/train myself to accept it as the correct way, but I don’t understand the logic behind it.
Any help explaining that would be greatly appreciated.
Thanks,
Keenan

The i++ tells the for loop to increment i for the next iteration. If you want to start ourArray at 1, then you will need to initialize i to 1 with the current code.

OR

Rewrite the code as follows and use ++i which will increment before the push.

for (var i = 0; i < 4;) {
ourArray.push(++i);
}
console.log(ourArray); // [1, 2, 3, 4]
1 Like

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

1 Like

Hi,

In the for loop, the third statement i++ runs after the { code block }.

Tried to get this response in earlier but got caught by emergency maint. I can see this has already been answered, but I really just want to participate and reinforce what I’ve learned.

sev

1 Like