My recursive code consists of two pieces aiming to print out half of the array recursively until we reach arrays of length 1. Surprisingly, the code without variable assignment runs infinitely, while the code with variable assignment behaves as expected.
Any ideas why this is happening?
Runs infinitely, CAUTION
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 initially thought that maybe mutability plays a role here, but I can't see how it would cause this effect. I presumed that we pass a new array into the function every time it's called...