Chunky Monkey - difference between i + size and i += size in a for loop

Tell us what’s happening:
Hi there, looking for help to explain to me why is this so. I figured out that if I put i + size in the for loop instead of i+=size, it creates an infinite loop of [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]... as result. I’ve read through the documentation but can’t quite understand what makes the difference. If you do, can you explain it to me? Thank you so much!

Your code so far


function chunkArrayInGroups(arr, size) {
  let result = [];
  for (let i = 0; i < arr.length; i+size) {
    result.push(arr.slice((i), (size + i)));
  }
  return result;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey

1 Like

The difference is, one version has an assignment operator and the other doesn’t. Javascript will never explicitly replace a value in a variable, you need to assign a new value. so i+size will evaluate the value of i plus the value of size, but not assign it to any variable namespace. On the other hand, i += size is saying ‘take the current value of i and increment it by size, and assign that value back into i.’

i += size is exactly the same as i = i+size, while i+size is missing any sort of assignment (=) operator.

1 Like

Thank you so much! That made sense :slight_smile:

1 Like