How does this if-else statement inside a function work?

  • A+
Category:Languages

I've been completing challenges on FreeCodeCamp and stumbled upon this solution for an algorithm. Can't comprehend how the if else statement works here.

function chunkArrayInGroups(arr, size) {    var temp = [];   var result = [];    for (var a = 0; a < arr.length; a++) {     if (a % size !== size - 1)       temp.push(arr[a]);     else {       temp.push(arr[a]);       result.push(temp);       temp = [];     }   }    if (temp.length !== 0)     result.push(temp);    return result; } 

Why is temp = [] at the end of the else block?

 


temp = [] means "reset the temp variable to an empty array"


in the if block, the arr[a] element is pushed at the end in the temparray.

in the else block, the same happens AND the whole current temp array is added at the end of the big result array of arrays, and the temparray is reset to the empty array.

Cannot say much more since there is not data or context written in your question. Hope this has answered your question.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: