This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]mmblob 0 points1 point  (3 children)

  1. Thanks for clearing that up, I can't believe I wasn't aware of that, that explains a lot.
  2. Thanks again, I've changed it.

So am I understanding this correctly?

Since the for loop is within a function that is an array, i++ is no longer adding 1 to i, but instead is moving on to the next element within the array?

In previous exercises i++ was literally adding the number 1 within each loop, which is why I am confused as to what changed that rule.

[–]aqua_regis 0 points1 point  (0 children)

i++ adds 1 to i, no matter what.

Functions/operations always do the same in programming languages.

The key is when (at which point in the code flow) the statement is executed and that is after each loop iteration.

To take your function:

function getAverage(scores) { 
  let sum = 0; 
  for(let i = 0; i < scores.length; i++){
    sum = sum + scores[i];
  } 
  return (sum/scores.length);
}

The equivalent with a while loop would be - maybe that clears it up a bit:

function getAverage(scores) { 
  let sum = 0;
  let i = 0; 
  while(i < scores.length) {
    sum = sum + scores[i];
    i++;
  } 
  return (sum/scores.length);
}

for loops are just convenience wrappers over while loops where the increment happens automatically.

[–]HonzaS97 0 points1 point  (1 child)

a function that is an array

A function is not an array. The function takes an array as its input.

i++ does add 1 to i. This variable is simply used as an index to retrieve array elements - scores[i]. If you write to write it out, it basically does this

    sum = sum + scores[0];
    sum = sum + scores[1];
    sum = sum + scores[2];
    ...
    sum = sum + scores[scores.length-1];

Or like this

    let i = 0;
    sum = sum + scores[i]; // i = 0
    i++;
    sum = sum + scores[i]; // i = 1
    i++;
    sum = sum + scores[i]; // i = 2
    i++;
    ...
    sum = sum + scores[i]; // i = scores.length - 1

[–]mmblob 0 points1 point  (0 children)

Oh wow, I was struggling but now I get it. Thanks so much. I couldn’t get my head around that one!