Basic JavaScript - Iterate Through an Array with a For Loop

so yeah why does it count up the index numbers of the array,
and not just count the indexes of the array ?
5 indexes that count up 20 ?

and why as usual is that use for ?

Your code so far

// Setup
const myArr = [2, 3, 4, 5, 6];

// Only change code below this line

var total= 0;

for (var i = 0; i < myArr.length; i++){
total = total + myArr[i];

Your browser information:

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

Challenge: Basic JavaScript - Iterate Through an Array with a For Loop

Link to the challenge:

If i=0 what is this value? If i=1 what is this value? Keep going up to i=4. Do you see what it is adding to total each time?

I will try to clear things up.

A for loop can be easily pulled apart into a while loop to explain things.

for (let i = 0 /*initialization*/; i<10 /*condition*/; i++/*increment/progress*/){
  total += i;

/* A for loop rewritten as a while loop */

let i = 0; /*initalizaiton*/
while (i<10 /*condition*/){
  i++ //increment/progression

Here are all the parts explained

  1. Initialization: Used for initalizaing a counter, usually i, to track how many loops you have completed. It is also completed only once before your loop happens (like the while loop example).

  2. Condition: A boolean expression that equates to true or false. If it is true, it will run a loop, otherwise, it will break out.

  3. Increment / Progress: Online, it is called an increment or decrement, but it can really be any operation, even multiplication and division. It just represents that your count variable is ‘progressing’ through your loop. This causes your counter to change, breaking the condition and exiting the loop.

A for loop is basically a while loop compressed, repeating a piece of code ‘while’ the condition is true. So what your telling your code up above to do is to access indexes 0, 1, 2, 3, 4 (the condition is the array’s length, so it will do all of them) values in the array and then it will add them to total. Because total is global, it won’t get reset when the loop resets, so your outcome is the elements added together.

A while loop is generally used for unknown amount of repeating (game loops, file searching, etc).
A for loop is used generally for repeating a certain amount of times before (testing a function 5 times) or during runtime (array.length: this can change throughout runtime)

One of the main uses is what you are doing now, going through each element in an array.

Hope this has been helpful!

yeah it did thanks :slight_smile:

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