0

let itemsArr = ["Milk", "Bread", "Potato"];
let quantityArr = [5, 2, 3];

for (i = 0; i <= itemsArr.length; i++) {
  if (i <= itemsArr.length)
    console.log(itemsArr[i] + " - " + quantityArr[i]);
}

it should
Print the following result:

Milk - 5
Bread - 2
Potato - 3

but why it is Print the following result:

Milk - 5
Bread - 2
Potato - 3
undefined - undefined

Please help!

Barmar
  • 741,623
  • 53
  • 500
  • 612

4 Answers4

5

Arrays are 0-indexed, so the last element's index is always length - 1. Therefore, you should update your loop as follows:

let itemsArr = ["Milk", "Bread", "Potato"];
let quantityArr = [5, 2, 3];

for (i = 0; i < itemsArr.length; i++) {
    console.log(itemsArr[i] + ' - ' + quantityArr[i]);
}

Notice that there is also no need to check the status inside of the loop using the if statement, since it will always evaluate to true.

For added points, you can remove the for loop entirely, and instead use forEach:

let itemsArr = ["Milk", "Bread", "Potato"];
let quantityArr = [5, 2, 3];

itemsArr.forEach((item, i) => {
  console.log(`${item} - ${quantityArr[i]}`);
});
BenM
  • 52,573
  • 26
  • 113
  • 168
1

Remember that itemsArr.length keeps number of all elements that are stored in an Array. For example for let itemsArr = ["Milk", "Bread", "Potato"]; it is 3. While index of array starts with 0 for Milk and ends with 2 for Potato.

This means that if you loop over the array you should use last index of an array, meaning that stop condition should look like for (i = 0; i < itemsArr.length; i++) or for (i = 0; i <= itemsArr.length - 1; i++)

This is common error that is being made even by experienced programmers (maybe in a little bit more complicated situations;-) It even has its own name off by one error - https://en.wikipedia.org/wiki/Off-by-one_error

Zychoo
  • 625
  • 2
  • 8
  • 25
1

I just want to add, that you can use forEach instead of for.

luisbar
  • 676
  • 5
  • 11
-5

Delete if(i <= itemsArr.length)

ken666
  • 1
  • 1