-1
var donuts = ["jelly donut", "chocolate donut", "glazed donut"];

for (var i = 0; i < donuts.length; i++) {
  donuts[i] += " hole";
  donuts[i] = donuts[i].toUpperCase();
}
Reyno
  • 6,119
  • 18
  • 27
  • 2
    The `i` allows you to access to the element in a array when the `i` is 0 you are accessing the first item on the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for – mgm793 Feb 28 '23 at 15:40
  • In the given code, i is used as an index to access each element of the donuts array using the square bracket notation (donuts[i]). – Hamid Shoja Feb 28 '23 at 15:46
  • `i` is not added to `donuts[i]` in the code. – user3840170 Feb 28 '23 at 16:37

4 Answers4

1

i represents the number (index) where the element is located in the array. You can notice it i is assigned the value of 0 when it is initialized in the for loop.

In the first iteration i is 0 so it is the same as saying donuts[0], in the next i will be 1 (since i++ is incrementing i by 1) we will looking at donuts[1] and so on until the i is less than the length of the array. Once i reaches same value as the length of the array the condition i < donuts.length will not be true anymore, and the loop will stop.

Another way to go about looping through every item in the array is using the forEach method. Here is a link talking more about it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

0

arr[i] refers to the (i-1) th element of that array. In this case, the loop goes through all its elements one by one, accessing each one by using the array index operator.

You can read more about arrays in JavaScript here.

avighnac
  • 376
  • 4
  • 12
  • So, donuts[i] means it affects all the arrays. Example donut[I] += "hole" means it iterates through the code and adds holes to the strings. right? – NAK DICKSON Feb 28 '23 at 16:03
  • @NAKDICKSON No `donuts[i]` just means 1 single donuts item based on the value of `i`, with `i` been the index. it's the for loop that changes `i` every time that makes it all donuts. – Keith Feb 28 '23 at 16:11
0

These are references to elements in the JavaScript array which are 0 based. Here I also add the value of i to each.

var donuts = ["jelly donut", "chocolate donut", "glazed donut"];
// reference to the first donut:
console.log("Before:", donuts[0]);
for (var i = 0; i < donuts.length; i++) {
  donuts[i] += " hole " + i;
  donuts[i] = donuts[i].toUpperCase();
}
console.log(donuts);
console.log("After:", donuts[0]);
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
0

If you're wondering why the letter I is used, it is possible to say that it refers to the index.