I have two pieces of recursive code, intending to recursively print out half of the array until we get to arrays of array length 1. The code without variable assignment runs infinitely while the code with variable assignment behaves as expected.
Any clues why this is the case?
Runs infinitely, CAREFUL
function half(arr) {
halfway = Math.floor((arr.length) / 2)
console.log(arr)
if (arr.length > 1) {
half(arr.slice(0, halfway));
half(arr.slice(halfway));
}
return
}
half([1, 2, 3, 4, 5]);
Does not run infinitely
function half(arr) {
halfway = Math.floor((arr.length) / 2)
console.log(arr)
if (arr.length > 1) {
var a = arr.slice(0, halfway);
var b = arr.slice(halfway);
half(a);
half(b);
}
return
}
half([1, 2, 3, 4, 5]);
I thought that maybe some kind of mutability might be at play here but I can't imagine how there would be run on effect. I thought that we were passing what is effectively a whole new array into the function every time it gets called...