freeCodeCamp Challenge Guide: Iterate with JavaScript For Loops

Iterate with JavaScript For Loops


Hints

Hint 1

for(var i = 0; i < 5; i++) {  // There are 3 parts here

There are three parts to for loop. They are separated by semicolons.

  1. The initialization: var i = 0; - This code runs only once at the start of the loop. It’s usually used to declare the counter variable (with var) and initialize the counter (in this case it is set to 0).

  2. The condition: i < 5; - The loop will run as long as this is true. That means that as soon as i is equal to 5, the loop will stop looping. Note that the inside of the loop will never see i as 5 because it will stop before then. If this condition is initially false, the loop will never execute.

  3. The increment: i++ - This code is run at the end of each loop. It’s usually a simple increment (++ operator), but can really be any expression. It is used to move the counter (i) forward (or backwards, or whatever).


Solutions

Solution 1 (Click to Show/Hide)
var ourArray = [];
for (var i = 0; i < 5; i++) {
  ourArray.push(i);
}

var myArray = [];
for (var i = 1; i < 6; i++) {
  myArray.push(i);
}
1 Like

The tricky part of this one for me was the i = 0.
if i =0 then the array starts with 0 and the challenge wants you to start at 1.

So I changed i = 1 and then i < 6 so the result was an array [1, 2, 3, 4, 5]

for (var i = 1; i < 6 ; i++) {

7 Likes

This worked for me :slight_smile:

var myArray = [];
for(var i=1; i<=5; i++){
myArray.push(i);
}

6 Likes

I’ve solved the challenge but I don’t understand why I’ve to put myArray.push(i).

What’s the use of push here? I thought push is for us to attend the data to the end of an array but I don’t see how it’s applied here.

2 Likes

You’re totally correct - .push() adds the value to the end of the array. In our case, since we have an empty array to begin with, when we push a value, it becomes the only value in the array. However, it’s important to remember that we are always adding values to the end of the array.

So, what our loop

var myArray = [];

for (var i = 1; i <= 5; i++) {
   myArray.push(i);
}

does is this:

myArray = [1], 
myArray = [1,2],
myArray = [1,2,3],
myArray = [1,2,3,4],
myArray = [1,2,3,4,5]
9 Likes

To push the values 1 through 5,it means start looping at 1 through 5( inclusive).Like this (var a = 1;a <= 5;a++)

// Example
var ourArray = [];

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

// Setup
var myArray = [];

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

Iteration in JavaScript is so great and easy! :stuck_out_tongue:

My code here:

// Setup
var myArray = [];

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