Iterate with JavaScript For Loops: erroneous output

Iterate with JavaScript For Loops: erroneous output
0

#1

Tell us what’s happening:

  1. My code doesn’t give correct output.
  2. in the previous exercise (while loop), variable i was declared outside the loop, but this step was skipped in for loop exercise. Isn’t it necessary to declare variables outside the loop?

Your code so far


// Example
var ourArray = [];

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

// Setup
var myArray = [];

// Only change code below this line.
for (var j = 1; j < 5; j++) {
    myArray.push(j);
}   

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops


#2
  1. You want 1 through 5. Look at when your loop stops: you’re telling it to finish before it gets to 5.
  2. You are declaring the counter - var i = 0 and var j = 1 are in the definition for each. With while loops, only have the end condition goes in the brackets: it’s not possible to declare the start condition in the brackets so you have to put it before. You can do the same with a for loop but it looks weird and would be confusing and pointless:
    var i = 0;
    for ( ; i < 5; i++) {
      ...