 # Chunky Monkey help with the infinite

Tell us what’s happening:
I just don’t understand why this won’t work, how is it an infinite loop?

*edit, I solved it on my own with a whole other approach, but I still don’t understand what was previously wrong…

``````
function chunkArrayInGroups(arr, size) {
var array = [];
var iter = Math.ceil(arr.length / size);

for (var i=0; i<iter; i++) {
//newCodeBelow
var x = i*size;
array.push(arr.slice(x, x+size));
//newCodeAbove,oldCommentedCodeBelow
/* for (var x=0; x<=arr.length-size; x+size) {
for (var z=size; z<=arr.length; z+size) {
array.push(arr.slice(x, z));
}
}*/
}

return array;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2)
``````

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 OPR/50.0.2762.67`.

https://www.freecodecamp.org/challenges/chunky-monkey

Your original code (with the code not comment out) does the following.

1. Enter first for loop, i = 0

2. Enter second for loop, x = 0;

3. Enter third for loop, z = 2

4. 1st iteration of third for loop - Since z is <= arr.length (4), you push [‘a’, ‘b’] into array. At this point array looks like [ [ ‘a’, ‘b’ ] ]

5. 2nd iteration of third for loop - z = 2 and since z is <= arr.length (4), you push [‘a’, ‘b’] into array. [ [ ‘a’, ‘b’ ], [ ‘a’, ‘b’ ] ]

This continues forever with an additional [‘a’, ‘b’] being added to array, because the third for loop condition never evaluates to false.

Actually, after each loop, z is increased by size:
for (var z=size; z<=arr.length; z+size)
Therefor, z is never smaller or equal then the length of the array, z just keeps on getting bigger.
This happens with x before z too, so that’s why you’re getting an infinite loop warning at the line with the z-loop.

Edit: whoops my bad, wrong calculation there. z+size doens’t do anything in this loop, therefor @RandellDawson’s answer is correct. z is always equal to 2, which is always shorter than the length of arr (pirates!).