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...
Because it lacks var, let and const, halfway has global scope, as if you wrote window.halfway. As a result, all recursive calls modify and use the same single variable.
In the 1st function the value is changed in the first recursive call before it can be used in the second recursive call. In my testing this actually led to a kind of Stack Overflow error (or rather a Maximum call stack size error), very appropriate for this site :-).
In the 2nd function the value is used twice before the recursive calls start, and then it gets modified by both after each other.
Issue solved by using const:
function half1(arr) {
const halfway = Math.floor((arr.length) / 2)
console.log(arr.toString())
if (arr.length > 1) {
half1(arr.slice(0, halfway));
half1(arr.slice(halfway));
}
return
}
function half2(arr) {
const halfway = Math.floor((arr.length) / 2)
console.log(arr.toString())
if (arr.length > 1) {
var a = arr.slice(0, halfway);
var b = arr.slice(halfway);
half2(a);
half2(b);
}
return
}
const data = [1, 2, 3, 4, 5];
half1(data);
console.log("------------------------")
half2(data);
Final note: the whole problem would have been detected and prevented by the JS compiler if you had put 'use strict'; on top of your code. I don't really like how clumsily this directive works (why does putting a "dead and unused" string on top of your code have such a special and far-reaching effect?), but we'll have to make use of what we can get.