0

Here is the total for loop including the initial array "myArray". I understand the logic for the loop and iteration, but I was wondering the term for the [i] when assigning the results of the loop to a variable or returning the loop.

const myArr = [2, 3, 4, 5, 6];
let total = 0

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

console.log(total)

I was able to complete the loop. May someone please help to deepen my understanding of the name and meaning of the myArr[i] which I assigned to the total using the addition assignment operator. Does it represent the final result of the loop? Thank you very much! :)

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • 1
    i is the index. – DownloadPizza Nov 22 '22 at 19:40
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for – isherwood Nov 22 '22 at 19:42
  • `[i]` is how you access an `index` of an array. During your loop, `i` is `0` through `4`, or `myArray[0]` through `myArray[4]` – Tim Lewis Nov 22 '22 at 19:42
  • `myArr[i]` itself is a _MemberExpression_. See [What does this symbol mean in JavaScript?](/q/9549780/4642212) and the documentation on MDN about [expressions and operators](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators) and [statements](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements). For individual expressions and subexpressions, see the specification: [_Script_ goal symbol](//tc39.es/ecma262/#prod-Script) and [_Module_ goal symbol](//tc39.es/ecma262/#prod-Module). Go through the grammar productions step by step. – Sebastian Simon Nov 22 '22 at 19:50

2 Answers2

3

You probably mean Property accessor

Konrad
  • 21,590
  • 4
  • 28
  • 64
  • Thank you very much Konrad! Property accessors are what I was looking for. Specifically bracket notation when in an object[expression]. – thelinuxlobster Nov 23 '22 at 19:46
0

total = 0

Starting the loop, the loop will be done 5 times as it's the length of myArr
To notice that the first element of an array is at position 0 (or index 0) and not 1

iteration 1
i = 0
total = total + the value of myArr at position i, so total = 0 + myArr[0] => 2

iteration 2
i = 1
total = total + the value of myArr at position i, so total = 2 + myArr[1] => 5

iteration 3
i = 2
total = total + the value of myArr at position i, so total = 5 + myArr[2] => 9

iteration 4
i = 3
total = total + the value of myArr at position i, so total = 9 + myArr[3] => 14

iteration 5
i = 4
total = total + the value of myArr at position i, so total = 14 + myArr[4] => 20

end of loop
total = 20

BenoitB
  • 31
  • 6