# Can anyone explain my "by mistake" solution ? - Algorithm Chunky Monkey

Can anyone explain my "by mistake" solution ? - Algorithm Chunky Monkey
0

#1

Hi everyone,

I was struggling to find a solution to this challenger when “by mistake” it worked; now I can’t understand the FOR LOOP logic here.

`for ( var i = 0; arr.length; i+=size)` // whats the meaning of this? Cause var i isn’t < or > or <= >= arr.length.

Best regards.
Paulo.

Entire Solution below .

`function chunkArrayInGroups(arr, size) {
var secondArray = [];

for ( var i = 0; arr.length; i+=size) {
secondArray.push(arr.slice(0, size));

//secondArray.push(arr.slice(size));

arr = arr.slice(size);

}

return secondArray;
}

chunkArrayInGroups([“a”, “b”, “c”, “d”], 2);

#2

Second parameter in `for` loops gets evaluated before each loop, if it evaluates to truthy, loop gets executed if it is falsy, loop stops.

In each loop you are changing the array `arr` by slicing it and every time `arr.length` gets smaller (first it’s 4, then 2 and then 0 which evaluates to false, so the loop stops).

#3

Thanks for your replied @jenovs ; I thought I was obliged to put

i < arr.lenght. // or i > arr.length

to be evaluated by > `for loop` . so just to clarify:

In the first time, > `( var i = 0; arr.length; i+=size)`

var i = 0,
arr.lenght = 4 ----- “the four elements for the array” ;
and in each loop i ++ by size; ok…

so in this process it doesn’t matter the size of the `var i`; is this correct ? cause var i it’s not being evaluated.

#4

Correct!

You can check the syntax of a for loop and you’ll see that all the expressions are optional.

So this is a valid `for` loop:

``````var i = 0;
for ( ; ; ) {
console.log(i)
i++
if (i > 5) break;
}
``````

#5

Ok; I got it.

Thanks a lot @jenovs ; I appreciated your help.