Iterate Odd Numbers With a For Loop

Iterate Odd Numbers With a For Loop
0.0 0

#1

Tell us what’s happening:

Your code so far


// Example
var ourArray = [];

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

// Setup
var myArray = [];
for ( var i = 1; i < 10; i+=1){
myArray.push(i);
}
// Only change code below this line.


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36.

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


#2

You did not ask a question, but I assume you are wondering why your code does not satisfy the requirements of the challenge.

It does not work, because your code pushes the numbers 1 through 9 into myArray, instead of pushing the odd numbers 1 through 9 into myArray. Your for loop iterator i += 1 simply adds 1 each time to i. Think about what you need to add to i, to make your code work correctly.

With your code, myArray looks like:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

and it should look like:

[1, 3, 5, 7, 9]

#3

Remember you control the FOR loop conditions.
for (var i = 0; i < 10; i += 2)

You can start your variable (i) at any number (it does not have to be zero, the condition to exit the loop (could be until i =20, or while its under 100, etc) AND also, how the increment of the variable will be if any. And this can be as complex as needed. Instead of i+=2, it could be a more complex formula or even i += (x+y) (a combination of variables).