Potential Infinite Loop!


First: What is Potential infinite Loop ??
Second: Why this code gives me this kind of error, exactly at this line (( result.push(arr.slice(i,i + size)); ))

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var result = [];
  for (var i = 0 ; i+size <= size ; i + size){
    result.push(arr.slice(i,i + size));

  return result;

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);


A potential infinite loop means that a loop (a for loop in this case) might run “forever” and freeze your browser.

The problem is that you are not updating i in your for loop. Instead of doing i = i+1 or whatever logic to update i, you say i + size which doesn’t change i. So i will remain zero, and i + size <= size will always return true, which results in a never ending for loop.


I am not sure that I understand what you mean! even if I made it i <= size , it gives the same error. And whta’s difference between updating i with a 1 or the size value.


The updating with 1 was just an example. The point is that you are not updating i. To update a variable you will have to do something like i = size or i = i+size or whatever you want it to be. But you are only saying i+size which doesn’t update anything.


Ops :smiley:I got it. Thank you man, you really helped. This was a nightmare for 2 days


The loop control statement - the part in parentheses after the for keyword - is a notational convenience that allows three expressions commonly needed for looping to be written together - the three expressions still have to be valid statements on their own - e.g. an update to any variable in the third expression requires an assignment say i=i + 1 or i+=1 or ++i etc - the control statement only controls when each of the three expressions is executed relative to the body of the loop

This is fleshed out in the post below


That help too.Thank you.