Search code examples
javascriptalgorithmloopssplice

How does while loop work without a condition?


I understand that it's removing the first 3 elements of the array and adding them to the new array. But how does the function continue to add ensuing chunks of the array to the new array variable?

How does the while loop work without proper conditions?

How does it work in collaboration with splice() here?

function chunkArrayInGroups(arr, size){
  let newArr = [];
  while(arr.length){
    newArr.push(arr.splice(0, size))
  }
  return newArr;
}

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

Solution

  • The condition is while(arr.length). The while loop will run while that condition is truthy. In JavaScript every condition is truthy unless it is one of the following:

    false

    0 (zero)

    '' or "" (empty string)

    null

    undefined

    NaN (e.g. the result of 1/0)

    In your case the while loop will run while the array has elements in it (arr.length is greater than zero), because if the arr.length is zero the while loop will stop executing.

    arr.splice on the other hand is removing one element from arr every time it is executed (it is changing the arr length). So when there are no elements left in the arr (because arr.splice removed them all) the while loop will stop.