Code explanation help

I’m struggling to understand how the code below works. Could someone please help explain :

  1. What makes the loop go from array[value1} to array[value2], etc.

  2. What gives the loop access to each of the values within the array so that it can add them to the sum?

The only guess I have is that somehow using array.length in a loop automatically exposes each of the individual values.

Thanks in advance :slight_smile:

const thisArr = [2, 3, 4, 5, 6];

let sum = 0;
for (let p = 0; p < myArr.length; p++) {
sum += thisArr[p];

}

Look at the code inside the loop.
You have a reference to the array there in the form
thisArr[p]

The bracket notation allows us to index into the array using the index value p

While p is increasing from 0 to start and then goes up and up till it reaches the value of the length of the array at which point the loop conditional gives a false and shuts off the loop.

That makes complete sense now. I think my brain is broken. Probably never was functional to begin with. Thanks a lot!

1 Like

Sorry about those typos!

No worries! I was so focused on the explanation that I didn’t even notice them haha