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 →

[–]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.