2

While going through a blog written for arrays in C++, a question arose.

//...
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for(int i = 0; i< v.size(); i++){
     v.push_back(v[i]);
}

What will happen above is it will get into an infinite loop as the size of the vector would keep on increasing.

Similar case would happen in case of JS if a plain for loop is used :

for(let i =0; i< arr.size; i++){
    arr.push(arr[i])
}

But this wouldn't happen in case of a forEach loop. Like how is forEach then implemented. I want to know why forEach stops adding to the array and for doesn't after the first three elements.

  • Does this answer your question? [What is the difference between for and foreach?](https://stackoverflow.com/questions/10929586/what-is-the-difference-between-for-and-foreach) – Kaneki21 Aug 23 '22 at 04:57
  • No i want to know why forEach loops over only three elements and for gets into an infinite loop. How is this behaviour implemented in forEach ?? –  Aug 23 '22 at 05:43

2 Answers2

1

Think about how you would implement a forEach function with the same behaviour.

If you just wanted to ensure that you only iterate "starting length" amount of times, then you could assign the length before the for statement, and use that in the loops condition:

function customForEach(array, callback) {
  const startingLength = array.length;
  for (let i = 0; i < startingLength; i++) {
    callback(array[i], i, array)
  }
}

Which to my knowledge mirrors the behaviour of Array.forEach

Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
0

For Loop: The JavaScript for loop is used to iterate through the array or the elements for a specified number of times. If a certain amount of iteration is known, it should be used.

forEach loop: The forEach() method is also used to loop through arrays, but it uses a function differently than the classic “for loop”. It passes a callback function for each element of an array together with the below parameters:

  • Current Value (required): The value of the current array element
  • Index (optional): The index number of the current element
  • Array (optional): The array object the current element belongs to

We need a callback function to loop through an array by using the forEach method.

Please check more details here

Steve Gerrad
  • 354
  • 1
  • 8